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 if Statements

00:00 In this lesson, you’ll see how not can be used in the condition for an if statement. When you’re using a not in an if statement, it usually looks like this.

00:12 You want to check if some condition is not true. So in Python you write if not condition so that if the condition is false, then the not of it will be true, and Python will execute the code in the if block.

00:28 You would use a not in instances where writing the condition necessary to be True would be much more complicated. As an example, let’s suppose you’ve written a function to determine if a number is prime, such as this one, and a file called prime.py.

00:49 And you can see how it works. Without going into too many details, this simply checks lots of numbers one at a time if it’s a factor of the number in question. If it finds a factor, it reports False, but if it exhausts the list of potential factors to try and nothing works, then the function returns True to indicate the number is prime.

01:15 You can import that file …

01:21 and write a few statements to test it.

01:42 You create a variable, test if it’s prime, and display the result. Now consider a different but related question. What if you wanted to find out if a number was a composite number, in other words, a number bigger than one that isn’t prime? Writing a whole separate function would not be productive, when instead you can just use the word not in a condition to test it.

02:28 8 is not prime, so the function returns False. The not in front of the function call gives a result of True that the if statement sees, and so it prints the inside statement.

02:45 FYI, it’s well known that 1 is neither a prime or a composite number. So hopefully a programmer wouldn’t try to use this function in either case to determine if 1 were prime or not. That type of input checking is beyond the scope of this course.

03:03 In the next lesson, you’ll see another example of using not in an if statement condition.

Become a Member to join the conversation.