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?
No
**or parentheses, so*,//, and%run first, from left to right:7 // 2is3, then3 * 2is6. Separately,7 % 2is1.Then
+:6 + 1is7.Every number is an integer and no
/appears, so the result is the integer7.
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.
17 / 4is the float4.25:/always gives a float.17 // 417 % 42 * 3.0"4" + "2""-" * 5len("hello") * 2
Answer
The integer
4.The integer
1.The float
6.0: one float operand makes the result a float.The string
"42":+joins strings.The string
"-----":*repeats a string.The integer
10:len("hello")is5.
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.
2 ** 2 ** 3-2 ** 2(-2) ** 210 - 4 - 3100 / 10 / 27 // 2 ** 22 * 3 ** 2
Hint
** runs before everything except parentheses, and from right to left. Every other operator runs from left to right.
Answer
256:**runs from right to left, so it is2 ** 8.-4:**runs before the minus sign.4: the parentheses make the minus sign part of the number.3: from left to right,6 - 3.5.0: from left to right,10.0 / 2.1:2 ** 2is4first, then7 // 4.18:3 ** 2is9first, then2 * 9.
Worked example: tracing a program¶
Trace this program:
x = 5
y = x + 2
x = y * x
y = y - 1| After line | x | y |
|---|---|---|
| 1 | 5 | |
| 2 | 5 | 7 |
| 3 | 35 | 7 |
| 4 | 35 | 6 |
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 line | total | price | count |
|---|---|---|---|
| 1 | 0 | ||
| 2 | 0 | 4 | |
| 3 | |||
| 4 | |||
| 5 | |||
| 6 |
Answer
| After line | total | price | count |
|---|---|---|---|
| 3 | 4 | 4 | |
| 4 | 4 | 8 | |
| 5 | 12 | 8 | |
| 6 | 12 | 8 | 1 |
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?
inputgives the string"2.5".intreads only whole numbers, so it stops withValueError: invalid literal for int() with base 10: '2.5'.If the program should accept decimals,
floatis 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.
int("42")int("4.2")float("4.2")int(4.9)int(" 42 ")str(4) + str(2)int("forty-two")
Answer
42.A
ValueError:intdoesn’t read a decimal point.4.2.4: given a float,intcuts off the fraction; it doesn’t round.42:intignores spaces around the digits."42": both are strings, so+joins them.A
ValueError:intreads 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 metersRun 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.
Start with the text and a pair of curly braces for the value:
f"Distance: {distance} km". That printsDistance: 42.195 km.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.
The integer
price = 5asPrice: 5.00.The float
rate = 0.075asTax: 7.5%.The integer
population = 2500000as2,500,000.The string
name = "Ada"in a space 10 characters wide, lined up on the right, so thatf"[...]"prints[ Ada].
Answer
f"Price: {price:.2f}"..2fworks on integers too.f"Tax: {rate:.1%}".%multiplies by 100 and adds the percent sign.f"{population:,}".f"[{name:>10}]".
Exercise 2.8 (LO-2.4, ★★, about 15 minutes)¶
0.1 * 3 == 0.3isFalse. Explain why in one or two sentences, and write the comparison a program should use instead.Predict
round(4.5),round(5.5),round(-2.5), andround(1.005, 2). Then check them in the interactive interpreter.
Answer
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. Usemath.isclose(0.1 * 3, 0.3), afterimport math, which isTrue.4,6, and-2: each is exactly halfway, soroundgoes to the even neighbor. And1.0, not1.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.43Hint
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.
Explain where the cent went.
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
100 divided by 3 is 33.333…, and printing it with
.2frounds each share down to 33.33, a third of a cent less than the true share. Three shares lose a whole cent between them.10000 // 3is3333and10000 % 3is1, 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.34Counting 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.)