not

In the first section of this chapter, we talked about the logical operators and and or. There is one that we left out–not.

not acts a little bit differently than and and or.

We can think of and and or as taking two boolean values and combining them into one boolean value.

print(True and True)   # True
print(True and False)  # False
print(False and True)  # False
print(False and False)  # False


print(True or True)   # True
print(True or False)  # True
print(False or True)  # True
print(False or False)  # False

The not logical operator takes one boolean value and switches it to the opposite value.

print(not True)   # False
print(not False)  # True
print(not True)

The place where this gets complicated is when we use not in combination with other comparison and logical operators. This is because the portion of the logical expression affected by not is not always obvious.

Make a guess as to how the following expressions will evaluate before running them.

# TODO: guess the result of this expression, then run it!
# Guess:
# Actual:

print(not 7 < 2)

# TODO: guess the result of this expression, then run it!
# Guess:
# Actual:

print(not 7 < 2 and 5 < 10)

# TODO: guess the result of this expression, then run it!
# Guess:
# Actual:

print(not 7 < 2 and 5 > 10)

# TODO: guess the result of this expression, then run it!
# Guess:
# Actual:

print(not False == True and 5 < 10)

not is going to only apply to the first boolean value to the right of it (unless you use parentheses).

not’s precendence is going to be higher than and and or but lower than our comparison operators.