Using not in Boolean while Loops
00:00
Let’s take a look at an example of using not
in a while
loop. Just like with if
, use not
when there is a condition you want to be False
for a loop to iterate, because writing a condition that should be True
would be more complicated.
00:20 Suppose you’re writing a game or some other type of interactive program, and you want to personalize the experience for the player by having them enter their name. You don’t want the game to continue until they’ve done that.
00:32
So you can use a while
loop using a not
condition to ensure that this happens. Here’s a simple example. The player is supposed to enter a name at the input()
statement.
00:44
This action will repeat until the player types something at the prompt. Remember the empty string (""
) has a truth value of False
, so not name
will return True
if name
is still empty.
00:58
After the user types their name, the .strip()
method will remove any leading or trailing whitespace. So if they haven’t typed in anything meaningful, it will just return the empty string. Once the user types something other than blanks, the game will continue.
01:39 There’s the prompt. And as long as I keep hitting spaces, tab, or anything blank, it will keep asking for me to enter my name.
01:55
Once I type in a name, the loop ends. The effect of the method .strip()
? Notice at all the spaces before and after my name were removed.
02:12
Next, you’ll see examples of how to use the not
operator in other contexts.
Become a Member to join the conversation.