Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

These exercises practice what the Module 3 reading explained. They aren’t graded. Work each one on paper or in your head first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.

Worked example: evaluating a condition

With age = 70 and is_member = False, what is age >= 13 and age < 65 or is_member?

  1. Comparisons run first: age >= 13 is True, and age < 65 is False.

  2. and runs before or: True and False is False.

  3. Then or: False or is_member is False or False, which is False.

The condition is False: a 70-year-old who isn’t a member doesn’t match.

Exercise 3.1 (LO-3.1, ★, about 10 minutes)

With x = 4, y = 9, and name = "Sam", give the value of each condition. The first is done.

  1. x > 3 and y < 10 is True: both comparisons are true.

  2. not x == 4

  3. x > 5 or y > 5 and name == "sam"

  4. 3 < x <= 4

  5. name < "sam"

  6. x != 4 or not y < 9

Hint

Comparisons run first, then not, then and, then or. In item 3, which operator runs first, and or or?

Answer
  1. False: x == 4 is True, and not turns it into False.

  2. False: and runs first, and y > 5 and name == "sam" is True and False, which is False (capital S isn’t lowercase s). Then x > 5 or False is False or False.

  3. True: it means 3 < x and x <= 4, and both are true.

  4. True: S (83) comes before s (115).

  5. True: x != 4 is False, but not y < 9 is not False, which is True.

Exercise 3.2 (LO-3.1, ★★, about 10 minutes)

What does each snippet print? One of them stops with an error: which, and why?

  1. name = ""
    if name:
        print("Hello,", name)
    else:
        print("No name given")
  2. count = 0
    if count != 0 and 10 / count > 2:
        print("More than 2")
    else:
        print("Not more than 2")
  3. count = 0
    if 10 / count > 2 and count != 0:
        print("More than 2")
    else:
        print("Not more than 2")
Answer
  1. No name given: the empty string counts as false.

  2. Not more than 2: count != 0 is False, so and stops there, and the division never runs.

  3. It stops with ZeroDivisionError: division by zero. The division is now on the left, so it runs first, before and can see that count is zero.

Worked example: an unreachable branch

speed = int(input("Speed in km/h: "))
if speed > 50:
    print("Over the limit")
elif speed > 70:
    print("Far over the limit: report it")
else:
    print("Within the limit")
  1. For 80, speed > 50 is true, so it prints Over the limit and stops.

  2. Every speed above 70 is also above 50, so every such speed stops at the first branch. The second branch is unreachable.

  3. Check the narrowest condition first: swap the first two conditions and their blocks. Then 80 reports, 60 is over the limit, and 50 is within it.

Exercise 3.3 (LO-3.2, ★★, about 10 minutes)

A parcel under 1 kg is small, under 5 kg is medium, and 5 kg or more is large. Which branch of this script can never run? Fix it.

weight = float(input("Weight in kg: "))
if weight < 5:
    print("medium")
elif weight < 1:
    print("small")
else:
    print("large")
Answer

The small branch: every weight below 1 is also below 5, so it stops at the first branch and prints medium. With <, check the lowest threshold first:

weight = float(input("Weight in kg: "))
if weight < 1:
    print("small")
elif weight < 5:
    print("medium")
else:
    print("large")

Exercise 3.4 (LO-3.2, ★, about 15 minutes)

Write a script, password.py, that asks for a password and prints too short if it has fewer than 8 characters, ok if it has 8 to 11, and strong if it has 12 or more. Then run it with passwords of 7, 8, 11, and 12 characters.

Hint

len(password) is the number of characters. Start with the narrowest case.

Answer
password = input("Password: ")
if len(password) < 8:
    print("too short")
elif len(password) < 12:
    print("ok")
else:
    print("strong")

abcdefg (7) is too short, abcdefgh (8) and abcdefghijk (11) are ok, and abcdefghijkl (12) is strong. A real program wouldn’t show the password as it is typed; Python’s getpass module hides it, though the course doesn’t use it.

Exercise 3.5 (LO-3.1, LO-3.2, ★★, about 15 minutes)

A shop opens at 8 on weekdays and at 10 at weekends, and hour is a whole number of hours. Rewrite this nested decision as a single if and else, using and, or, and not. Check that your version prints the same for weekday and weekend hours of 7, 8, 9, and 10.

if is_weekend:
    if hour >= 10:
        print("Open")
    else:
        print("Closed")
else:
    if hour >= 8:
        print("Open")
    else:
        print("Closed")
Answer
if (is_weekend and hour >= 10) or (not is_weekend and hour >= 8):
    print("Open")
else:
    print("Closed")

The parentheses aren’t needed, because and runs before or, but they show the two cases. Both versions print Closed at 7, then Open from 8 on weekdays, and Closed until 10 at weekends. Which one is clearer is a judgment; here the flat one is shorter, and the nested one mirrors the way the rule is stated.

Worked example: choosing tests

A speed camera says OK up to 50 km/h, Warning from 51 to 60, and Fine above 60, for whole numbers. The answer changes between 50 and 51 and between 60 and 61.

SpeedWhyExpected
30Inside the first bandOK
50Last OKOK
51First WarningWarning
60Last WarningWarning
61First FineFine
90Inside the last bandFine

Exercise 3.6 (LO-3.3, ★, about 10 minutes)

A thermometer program prints ice below 0 degrees, water from 0 up to and including 99, and steam at 100 or above, for whole numbers. Write a table of tests, as in the worked example, that reaches every branch and tests both sides of both boundaries.

Answer
TemperatureWhyExpected
-20Inside the first bandice
-1Last iceice
0First waterwater
99Last waterwater
100First steamsteam
150Inside the last bandsteam

The four boundary tests are the ones that matter most; the two inside the bands are optional when the boundary tests already reach every branch.

Exercise 3.7 (LO-3.3, ★★, about 10 minutes)

Someone wrote the thermometer from Exercise 3.6 like this, and tested it with -20, 50, and 150. All three tests passed. Find the mistake, and say which test from your table catches it.

temperature = int(input("Temperature: "))
if temperature < 0:
    print("ice")
elif temperature <= 100:
    print("water")
else:
    print("steam")
Answer

temperature <= 100 puts 100 in the water band; it should be temperature < 100, or temperature <= 99. The test with 100 catches it: it expects steam and gets water. None of -20, 50, and 150 sits on a boundary, which is why they all passed.

Exercise 3.8 (LO-3.1, LO-3.2, LO-3.3, ★★★, about 25 minutes)

Write a script, rps.py, that asks two players for a move in rock, paper, scissors (rock, paper, or scissors) and prints Draw, Player 1 wins, or Player 2 wins. Rock beats scissors, scissors beats paper, and paper beats rock.

Then type lizard as one move. What does your script print, and how would you change it so that it prints Invalid move instead?

Hint 1

Handle the draw first. Then there are exactly three ways for player 1 to win; every other pair means player 2 wins.

Hint 2

A condition can run over several lines if it is inside parentheses.

Answer
first = input("Player 1: ")
second = input("Player 2: ")
if first == second:
    print("Draw")
elif (
    (first == "rock" and second == "scissors")
    or (first == "scissors" and second == "paper")
    or (first == "paper" and second == "rock")
):
    print("Player 1 wins")
else:
    print("Player 2 wins")

With lizard against rock, it prints Player 2 wins, because every pair that isn’t a draw or a player 1 win falls into the else. To reject bad moves, check them first:

valid_first = first == "rock" or first == "paper" or first == "scissors"
valid_second = second == "rock" or second == "paper" or second == "scissors"
if not (valid_first and valid_second):
    print("Invalid move")
elif first == second:
    ...

The rest stays the same. A good test plan has a draw, each of the three wins for each player, and an invalid move from each player: nine tests. Module 7 shows a shorter way to ask whether a value is one of several, with in.