Turning a condition around: not
The operator not turns a condition around: not of something true is false, and not of something false is true.
>>> not True
False
>>> not False
True
>>> not 3 > 5
TruePython works out the comparison before not, so not 3 > 5 means not (3 > 5). Often not is handy in front of a combined condition in parentheses. In the step about or, day == "Saturday" or day == "Sunday" checked for the weekend. With not in front, the same condition checks for a weekday:
day = "Tuesday"
if not (day == "Saturday" or day == "Sunday"):
print("The library opens at 8 today.")
The library opens at 8 today.The parentheses matter here: without them, the not would turn around only the first comparison, and the condition would be true on Sundays too.
Truth values in variables
You saw in part 1 that the value of a comparison, True or False, can be stored in a variable like any other value. With not, such a variable reads almost like English:
answer = input("Is the door locked? (yes/no) ")
locked = answer == "yes"
if not locked:
print("Remember to lock the door!")
print("Good night.")
noIs the door locked? (yes/no) no
Remember to lock the door!
Good night.The line locked = answer == "yes" first evaluates the comparison, then stores its value in locked. Here that value is False, so not locked is True.
Which goes first
When a condition mixes the operators, Python groups it as if there were parentheses around each comparison first, then around each not, then around each and, with or last. So a or b and c means a or (b and c), which can surprise you. (The grouping only decides which parts belong together. Python still reads the condition from left to right.) Children under 12 and seniors 65 or older should get a discount, but not on Sundays:
age = 8
day = "Sunday"
if age < 12 or age >= 65 and day != "Sunday":
print("Discount price")
else:
print("Full price")
Discount priceBecause and is grouped before or, Python reads the condition as age < 12 or (age >= 65 and day != "Sunday"), and a child gets the discount every day. Parentheses say what is meant: (age < 12 or age >= 65) and day != "Sunday". When a condition mixes and and or, add parentheses even where they aren't needed. They make the condition easier to read.