Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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:14 Let’s check this out.

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.