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 2 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: predicting a type and a value

What are the type and value of 7 // 2 * 2 + 7 % 2?

  1. No ** or parentheses, so *, //, and % run first, from left to right: 7 // 2 is 3, then 3 * 2 is 6. Separately, 7 % 2 is 1.

  2. Then +: 6 + 1 is 7.

  3. Every number is an integer and no / appears, so the result is the integer 7.

7 // 2 * 2 + 7 % 2 gives back 7, and the same holds for any whole number divided by any other: the whole units times the divisor, plus the remainder, is the number you started with.

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

Give the type and value of each expression. The first is done for you.

  1. 17 / 4 is the float 4.25: / always gives a float.

  2. 17 // 4

  3. 17 % 4

  4. 2 * 3.0

  5. "4" + "2"

  6. "-" * 5

  7. len("hello") * 2

Answer
  1. The integer 4.

  2. The integer 1.

  3. The float 6.0: one float operand makes the result a float.

  4. The string "42": + joins strings.

  5. The string "-----": * repeats a string.

  6. The integer 10: len("hello") is 5.

Exercise 2.2 (LO-2.1, ★★, about 10 minutes)

Predict the value of each expression, using the reading’s table of which operator goes first.

  1. 2 ** 2 ** 3

  2. -2 ** 2

  3. (-2) ** 2

  4. 10 - 4 - 3

  5. 100 / 10 / 2

  6. 7 // 2 ** 2

  7. 2 * 3 ** 2

Hint

** runs before everything except parentheses, and from right to left. Every other operator runs from left to right.

Answer
  1. 256: ** runs from right to left, so it is 2 ** 8.

  2. -4: ** runs before the minus sign.

  3. 4: the parentheses make the minus sign part of the number.

  4. 3: from left to right, 6 - 3.

  5. 5.0: from left to right, 10.0 / 2.

  6. 1: 2 ** 2 is 4 first, then 7 // 4.

  7. 18: 3 ** 2 is 9 first, then 2 * 9.

Worked example: tracing a program

Trace this program:

x = 5
y = x + 2
x = y * x
y = y - 1
After linexy
15
257
3357
4356

Line 3 uses y (7) and the old x (5), then makes x refer to 35. Line 4 changes y, and x stays 35, because nothing ties it to y.

Exercise 2.3 (LO-2.2, ★, about 10 minutes)

Finish the trace of this program. The first two rows are done.

total = 0
price = 4
total = total + price
price = price * 2
total = total + price
count = total // price
After linetotalpricecount
10
204
3
4
5
6
Answer
After linetotalpricecount
344
448
5128
61281

12 // 8 is 1. At the end, total is 12, price is 8, and count is 1.

Exercise 2.4 (LO-2.1, LO-2.2, ★★, about 15 minutes)

This program should split 4,000 seconds into hours, minutes, and seconds, and print 1 hours, 6 minutes, 40 seconds. Trace it, find which line gives a wrong value, and fix it.

total = 4000
hours = total // 3600
minutes = total // 60
seconds = total % 60
print(hours, "hours,", minutes, "minutes,", seconds, "seconds")
Hint

How many minutes does total // 60 count: the minutes left over after the whole hours, or every minute in the 4,000 seconds?

Answer

Line 3 gives 66, every whole minute in 4,000 seconds, including the 60 that make up the hour. The minutes must come from what is left after the hours: total % 3600 is 400 seconds, and 400 // 60 is 6.

minutes = total % 3600 // 60

% and // have the same precedence and run from left to right, so this needs no parentheses, though (total % 3600) // 60 says the same thing more plainly. seconds is already right: 4000 % 60 is 40.

Worked example: a conversion that fails

A script runs count = int(input("How many? ")), and the user types 2.5. What happens?

  1. input gives the string "2.5".

  2. int reads only whole numbers, so it stops with ValueError: invalid literal for int() with base 10: '2.5'.

  3. If the program should accept decimals, float is the right conversion. If it shouldn’t, the error is fair, but it would be kinder to tell the user what went wrong; Module 12 shows how.

Exercise 2.5 (LO-2.3, ★, about 10 minutes)

For each expression, give the value Python produces, or the kind of error it raises.

  1. int("42")

  2. int("4.2")

  3. float("4.2")

  4. int(4.9)

  5. int(" 42 ")

  6. str(4) + str(2)

  7. int("forty-two")

Answer
  1. 42.

  2. A ValueError: int doesn’t read a decimal point.

  3. 4.2.

  4. 4: given a float, int cuts off the fraction; it doesn’t round.

  5. 42: int ignores spaces around the digits.

  6. "42": both are strings, so + joins them.

  7. A ValueError: int reads digits, not words.

Exercise 2.6 (LO-2.3, ★★, about 15 minutes)

Write a script, rectangle.py, that asks for the width and the height of a rectangle in meters, and prints its area and its perimeter. The sizes may have decimals. With 2.5 and 4 typed, it prints:

Width in meters: 2.5
Height in meters: 4
Area: 10.0 square meters
Perimeter: 13.0 meters

Run it in VS Code’s terminal, and type the sizes yourself. Then run it again with a width of two, and read the error.

Hint

The perimeter is twice the width plus twice the height, or 2 * (width + height).

Answer
# Prints the area and perimeter of a rectangle.
width = float(input("Width in meters: "))
height = float(input("Height in meters: "))
print("Area:", width * height, "square meters")
print("Perimeter:", 2 * (width + height), "meters")

With two typed, float stops the script with ValueError: could not convert string to float: 'two'.

Worked example: an f-string

Write an f-string that prints the float distance = 42.195 as Distance: 42.2 km.

  1. Start with the text and a pair of curly braces for the value: f"Distance: {distance} km". That prints Distance: 42.195 km.

  2. One decimal is the format specification .1f, after a colon inside the braces: f"Distance: {distance:.1f} km".

It prints Distance: 42.2 km.

Exercise 2.7 (LO-2.4, ★, about 10 minutes)

Write an f-string for each line.

  1. The integer price = 5 as Price: 5.00.

  2. The float rate = 0.075 as Tax: 7.5%.

  3. The integer population = 2500000 as 2,500,000.

  4. The string name = "Ada" in a space 10 characters wide, lined up on the right, so that f"[...]" prints [ Ada].

Answer
  1. f"Price: {price:.2f}". .2f works on integers too.

  2. f"Tax: {rate:.1%}". % multiplies by 100 and adds the percent sign.

  3. f"{population:,}".

  4. f"[{name:>10}]".

Exercise 2.8 (LO-2.4, ★★, about 15 minutes)

  1. 0.1 * 3 == 0.3 is False. Explain why in one or two sentences, and write the comparison a program should use instead.

  2. Predict round(4.5), round(5.5), round(-2.5), and round(1.005, 2). Then check them in the interactive interpreter.

Answer
  1. 0.1 has no exact binary form, so the float stored for it is slightly off, and three times it is 0.30000000000000004, not the float stored for 0.3. Use math.isclose(0.1 * 3, 0.3), after import math, which is True.

  2. 4, 6, and -2: each is exactly halfway, so round goes to the even neighbor. And 1.0, not 1.01: the float stored for 1.005 is slightly below 1.005, so it isn’t halfway at all, and it rounds down.

Exercise 2.9 (LO-2.3, LO-2.4, ★★, about 20 minutes)

Write a script, bill.py, that splits a restaurant bill. It asks for the bill and the number of people, adds a 15% tip, and prints the tip, the total, and each person’s share, all with two decimals. With 84.60 and 3 typed, it prints:

Bill: 84.60
People: 3
Tip: 12.69
Total: 97.29
Each pays: 32.43
Hint

The tip is bill * 0.15. Read the number of people with int, since it is a whole number.

Answer
# Splits a restaurant bill, with a 15% tip, among several people.
bill = float(input("Bill: "))
people = int(input("People: "))
tip = bill * 0.15
total = bill + tip
print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each pays: {total / people:.2f}")

Without .2f, the total prints as 97.28999999999999.

Exercise 2.10 (LO-2.1, LO-2.4, ★★★, about 20 minutes)

Three friends split a bill of 100.00 with no tip. Each share prints as 33.33, but three times 33.33 is 99.99: a cent has gone missing.

  1. Explain where the cent went.

  2. Count the bill in cents, as the integer 10000. Use // and % to work out how many cents each person pays and how many cents are left over, so that the shares add up to exactly 100.00. Print the shares with two decimals.

Hint

10000 // 3 is each person’s whole share in cents, and 10000 % 3 is the number of cents no one has paid yet. Someone has to pay them.

Answer
  1. 100 divided by 3 is 33.333…, and printing it with .2f rounds each share down to 33.33, a third of a cent less than the true share. Three shares lose a whole cent between them.

  2. 10000 // 3 is 3333 and 10000 % 3 is 1, so two people pay 33.33 and one pays 33.34:

    cents = 10000
    share = cents // 3
    left_over = cents % 3
    print(f"Two people pay {share / 100:.2f}")
    print(f"One person pays {(share + left_over) / 100:.2f}")
    Two people pay 33.33
    One person pays 33.34

    Counting in whole cents keeps every amount exact, which is why programs that handle money often do it. (With two cents left over, as for 100.01 among 3 people, two people pay one cent more.)