Python Arena
Step 3 of 5

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.

In the Python interpreter
>>> not True
False
>>> not False
True
>>> not 3 > 5
True

Python 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.")
Output
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.")
Input
no
Output
Is 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")
Output
Discount price

Because 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.

Your task

Challenge 1 of 3

Drum practice is allowed from 8 to 21 o'clock. Fill in the blank so the program asks for quiet at every other hour:

Hour: 23
Quiet hours, no drums please.

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Children under 12 and seniors 65 or older get a discount, but never on Sundays. The program below gives a child the discount on Sundays too. Fix the condition.

Age: 8
Day: Sunday
Full price: 10 euros