Kodeclik Blog


Python’s If Not Operator

Python’s if not operator tests if some condition is not true and can be a succinct way to describe some types of program logic. It is useful when a variable records a certain condition but the conditional tests for the negation of that condition.
Here is a simple example of Python’s if not operator:
This results in:

if not with lists or strings

The expression following the not need not be boolean. It can be any list or string. Note that an empty list or empty string will evaluate to False and any other value will evaluate to be True.
Consider the following program:
This outputs:
On the other hand, with the below program:
we will get:
The same logic applies to lists:
will give:
On the other hand, with the below program:
we get:
Similar to strings and lists, the if not can be used with other iterables like dictionaries and tuples. In all these cases, it makes for more readable code.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.