13. Numbers and math — Homework solutions
The .py solution files are in
exercises/13/homework/solutions/.
Problem 1 — Rectangle area
Problem. Multiply width and height; print the result with a label.
How to think about it. Multiplication is
*. Store the product in a third variable, or use it
directly inside print with an f-string.
Worked solution.
width = 6
height = 4
area = width * height
print(f"Area: {area}")Common mistakes.
- Writing
width x heightorwidth times height. Neither is Python; the multiplication operator is*.
Problem 2 — Floor and ceil
Problem. Show 3.7,
math.floor(3.7), and math.ceil(3.7) on three
lines, plus a comment explaining the difference.
How to think about it. floor rounds
down; ceil rounds up. Both return
integers. For positive numbers, floor drops the decimals;
ceil adds one unless the number is already whole.
Worked solution.
import math
x = 3.7
print(x) # 3.7
print(math.floor(x)) # 3
print(math.ceil(x)) # 4
# floor rounds DOWN to the next integer; ceil rounds UP. For 3.7
# they sit on either side: 3 and 4.Common mistakes.
- Expecting
math.floorto modifyx. It does not. Like.upper(), it returns a new value and leaves the original alone. - Forgetting
import math. Python raises aNameError: name 'math' is not defined.
Problem 3 — Roll two dice
Problem. Roll two six-sided dice independently. Print each plus the total.
How to think about it.
random.randint(1, 6) gives a number from 1 to 6. Call it
twice — once per die — then add the two variables.
Worked solution.
import random
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
total = die1 + die2
print(f"Die 1: {die1}")
print(f"Die 2: {die2}")
print(f"Total: {total}")Common mistakes.
- Calling
random.randint(1, 6)once and re-using the number for both dice. The two rolls must be separate calls. - Forgetting
import randomat the top of the file.
Challenge — Hypotenuse
Problem. Given two short sides of a right triangle,
compute the hypotenuse with math.sqrt, and print all three
values with the hypotenuse rounded to two decimals.
How to think about it. The maths is
c = sqrt(a*a + b*b). Both a*a and
a**2 work. math.sqrt returns a float. For
rounded display, use an f-string with :.2f.
Worked solution.
import math
a = 3
b = 4
c = math.sqrt(a * a + b * b)
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c:.2f}")For a = 3, b = 4 the output is:
a = 3
b = 4
c = 5.00
Common mistakes.
- Writing
math.sqrt(a**2 + b**2)and seeing5.0instead of5.00. The maths is correct; formatting controls the decimal places.:.2falways shows two. - Forgetting
import math. Python raises aNameError.
Done?
Two chapters to go before the mini-project: Working with text lets you slice, search, and replace inside strings, and Getting input turns the keyboard into values. Then the character sheet project ties Part 3 together.