Confused with the "not" operator in while loops and if statements

931 views Asked by At

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?

4

There are 4 answers

0
Kirill Kosyrev On

I finally got it and maybe this will help someone else as well:

  1. In Python if variable is empty, i.e. = None or = "" - it is considered False (or Falsey to be more precise).
  2. 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.
  3. 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.
0
askman On

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.

0
chepner On

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.

0
Ghulam Muhammad On

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