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 your subtitle preferences 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 refer to our video player troubleshooting guide for assistance.

Using not in Non-Boolean Contexts

00:00 Now let’s look at an example outside of if and while statements where you might use the not operator.

00:09 A non-Boolean context is somewhere other than the condition of an if statement or while loop, usually when you want to change the value of a Boolean variable, often to indicate that the program has changed state in some way, and that Boolean variable will be tested in some upcoming if or while statement to determine that.

00:32 Here’s an example where you want a Boolean value to alternate between True and False because you have a while loop which has to alternate between different instructions.

00:42 So an initial attempt might look to something like this. The toggle variable is supposed to alternate between True and False. If it’s True, you do one set of instructions. If it’s False, you do something else.

00:57 At the end of when it’s True, it gets set to False. And at the end of when it’s False, it gets set to True. Remember, the test in a while loop is only checked at the beginning of each iteration.

01:08 So the effect of changing toggle won’t be noticed until we check the while condition again. There’s actually a better way to write this loop.

01:18 Since you’re changing the value of toggle in both parts, you can take that step out of each condition if you write the assignment statement properly. So now it will look like this.

01:31 It still does the # Do something... part if toggle is True and the # Do something else... part if toggle is False, but now there is just a single assignment statement setting toggle to the not of what it currently is.

01:46 So if toggle was True, it would become False. And if toggle was False, it will become True.

01:55 And this loop will alternate between something and something else, just like it did in the previous version, but now with a slightly improved design.

02:06 Next you’ll look at some of the best practices for using the not operator in Python.

Become a Member to join the conversation.