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?
In a while loop like this,
Nonewill effectively evaluate asFalse. As you say, thenotinverses this, turning it into aTruecondition, 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 asFalseand 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.