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?
Comparisons run first:
age >= 13isTrue, andage < 65isFalse.andruns beforeor:True and FalseisFalse.Then
or:False or is_memberisFalse or False, which isFalse.
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.
x > 3 and y < 10isTrue: both comparisons are true.not x == 4x > 5 or y > 5 and name == "sam"3 < x <= 4name < "sam"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
False:x == 4isTrue, andnotturns it intoFalse.False:andruns first, andy > 5 and name == "sam"isTrue and False, which isFalse(capitalSisn’t lowercases). Thenx > 5 or FalseisFalse or False.True: it means3 < x and x <= 4, and both are true.True:S(83) comes befores(115).True:x != 4isFalse, butnot y < 9isnot False, which isTrue.
Exercise 3.2 (LO-3.1, ★★, about 10 minutes)¶
What does each snippet print? One of them stops with an error: which, and why?
name = "" if name: print("Hello,", name) else: print("No name given")count = 0 if count != 0 and 10 / count > 2: print("More than 2") else: print("Not more than 2")count = 0 if 10 / count > 2 and count != 0: print("More than 2") else: print("Not more than 2")
Answer
No name given: the empty string counts as false.Not more than 2:count != 0isFalse, soandstops there, and the division never runs.It stops with
ZeroDivisionError: division by zero. The division is now on the left, so it runs first, beforeandcan see thatcountis 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")For 80,
speed > 50is true, so it printsOver the limitand stops.Every speed above 70 is also above 50, so every such speed stops at the first branch. The second branch is unreachable.
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.
| Speed | Why | Expected |
|---|---|---|
| 30 | Inside the first band | OK |
| 50 | Last OK | OK |
| 51 | First Warning | Warning |
| 60 | Last Warning | Warning |
| 61 | First Fine | Fine |
| 90 | Inside the last band | Fine |
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
| Temperature | Why | Expected |
|---|---|---|
| -20 | Inside the first band | ice |
| -1 | Last ice | ice |
| 0 | First water | water |
| 99 | Last water | water |
| 100 | First steam | steam |
| 150 | Inside the last band | steam |
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.