Using not in Boolean if Statements
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
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
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.
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.
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.
Become a Member to join the conversation.