09. The print toolkit — Homework solutions
The .py solution files are in
exercises/09/homework/solutions/.
Problem 1 — A stat row
Problem. Print three values on one line, comma-separated.
Worked solution.
print("Keiko", 7, 95)Output (spaces between the values):
Keiko 7 95
Common mistakes.
- Quoting the numbers.
7and"7"look alike but are different types; the problem wants numbers.
Problem 2 — A polished line
Problem. Build one exact sentence with an f-string.
How to think about it. Put the variables in
{} placeholders at the right positions, with the
surrounding text (spaces, words) as literal characters in the
string.
Worked solution.
name = "Keiko"
hp = 95
level = 7
print(f"{name} has {hp} HP at level {level}")Output:
Keiko has 95 HP at level 7
Common mistakes.
- Forgetting spaces around the words inside the f-string, giving
Keikohas95HPatlevel7. The spaces outside the{}braces are part of the string — put them exactly where you want them.
Problem 3 — Spaced out
Problem. Three lines, a blank line between each,
five print calls.
Worked solution.
print("Line one")
print()
print("Line two")
print()
print("Line three")Common mistakes.
- Writing
print(" ")(a space) instead ofprint()(nothing). Both look blank, butprint()says "empty line" plainly.
Challenge — Receipt
Problem. Print a small receipt: item lines, a blank line, then a total.
Worked solution.
apple = 3
bread = 2
milk = 4
total = apple + bread + milk
print(f"apple: {apple}")
print(f"bread: {bread}")
print(f"milk: {milk}")
print()
print(f"Total: {total}")Output:
apple: 3
bread: 2
milk: 4
Total: 9
Common mistakes.
- Typing the total as a literal
9instead of computing it. A computed total updates when a price changes; a typed one won't.
Done?
You can now show values exactly how you want. The last chapter of this part — Reading error messages — covers the red text Python prints when something breaks.