'Confused with the "not" operator in while loops and if statements
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
I finally got it and maybe this will help someone else as well:
- In Python if variable is empty, i.e.
= 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.- In this case we set name
= 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | askman |
Solution 2 | chepner |
Solution 3 | Ethan |