Reputation: 1
So I'm a total beginner when it comes to Python and the "not" operator is kinda confusing me. So i was watching a BroCode video and he wrote this code:
name = None
while not name:
name = input("Enter your name: ")
print("Hello, "+name)
My question is: Doesn't this mean; while name is not nothing, do this? Isn't "not" supposed to make things opposite? So by that logic this code is not supposed to work. The condition of the while loop is that the name needs to be something, but it's not, so why does it even execute?
Upvotes: -1
Views: 1766
Reputation: 39
Python is kinda like english so when you say
while not name:
input("Enter your name")
It basically says that it would repeat until it's not the name variable, which is None.. Summary: It says to repeat UNTIL the variable name is not None
Upvotes: 0
Reputation: 1
I finally got it and maybe this will help someone else as well:
= None
or = ""
- it is considered False (or Falsey to be more precise).While
means While True and works as long as chosen condition is True. While not
basically means While False and works as long as set condition is False.= False
and say: as long as the name is False - do the loop. As soon as we add anything to the name through input - the name becomes True and the loop is ended.Upvotes: 0
Reputation: 532418
not
simply negates the "truthiness" of its arguments. None
and empty strings are considered falsey, while non-empty strings are considered truthy.
An improved version of this code would initialize name
to the empty string; there's no particular reason to care abut the distinction between None
and ""
, when not None
is only going to be evaluated once. (input
will always return a str
, empty or no.)
But a better version would only make one assignment to name
.
while True:
name = input("Enter your name: ")
if name:
break
The loop is guaranteed to execute at least once, so name
will always be defined once the loop exits. There's no need to initialize the value before the loop. As an added bonus, you can test the string's truthiness directly, rather than the negated truthiness.
Upvotes: 0
Reputation: 516
In a while loop like this, None
will effectively evaluate as False
. As you say, the not
inverses this, turning it into a True
condition, and making the loop run.
So what happens here is the loop is reached, and as there has been no input, and as name = None
, the condition passes and the loop body is entered. If the user enters an empty string, the next loop will again evaluate this as False
and run the loop again until a valid, non-empty string is entered.
So this is a simple way of ensuring that a string is entered.
Upvotes: 0