15. Getting input — Homework solutions
The .py solution files are in
exercises/15/homework/solutions/.
Problem 1 — Greet by name
Problem. Prompt with input(), read a
name, greet with an exclamation mark.
How to think about it. Two lines: read the name (the
prompt is passed directly to input()), then print the
greeting. The exclamation mark goes inside the string, after the
variable.
Worked solution.
name = input("First name: ")
print(f"Hello, {name}!")Common mistakes.
- Forgetting the trailing space in the prompt.
"First name:"jams the cursor against the colon;"First name: "leaves room.
Problem 2 — Sum of two
Problem. Read two numbers; print
a + b = c.
How to think about it. Two prompts, two reads, each
wrapped in int(). Build the output with an f-string.
Worked solution.
a = int(input("First number: "))
b = int(input("Second number: "))
c = a + b
print(f"{a} + {b} = {c}")Common mistakes.
- Skipping
int(). The values stay strings, soa + bgives string concatenation instead of addition:"3" + "4"is"34", not7. - Wrapping
int()around the prompt string instead of the result ofinput().int("First number: ")raises aValueErrorimmediately.
Problem 3 — Years to retirement
Problem. Compute 65 - age and print a
labelled sentence.
How to think about it. Prompt, read, convert,
subtract, print. Mind the order: 65 - age, not
age - 65.
Worked solution.
age = int(input("Your current age: "))
years_left = 65 - age
print(f"You have {years_left} years until retirement.")Common mistakes.
- Doing
age - 65, which prints a negative for everyone under 65. Subtraction is not commutative — order matters.
Challenge — BMI
Problem. Prompt for height and weight (decimals), compute BMI, print it to one decimal place.
How to think about it. Two prompts, two reads, both
through float() because the values have decimal points.
weight / (height * height) gives a float; :.1f
in the f-string shows one digit after the decimal.
Worked solution.
height = float(input("Height in metres (e.g. 1.78): "))
weight = float(input("Weight in kg (e.g. 72.5): "))
bmi = weight / (height * height)
print(f"BMI: {bmi:.1f}")Common mistakes.
- Using
int()instead offloat(). Heights like1.78are not integers;int("1.78")raises aValueError. - Forgetting the parentheses in
height * height. Without them,weight / height * heightruns left to right: divide by height, then multiply by it again — the heights cancel and you get weight back. - Entering height in centimetres (like
178) instead of metres (1.78). BMI uses metres, as the starter prompt says.
Done?
Every Part 3 chapter is done. The mini-project — the Character Sheet — uses everything from chapters 11 to 15.