Chapter 8: Input and Output — Solutions

Worked solutions to the 5 Find the Bug exercises in Chapter 8: Input and Output. Each one names the kind of bug, explains why the original misbehaved, and shows the corrected program.

Solutions stay folded until you open them — try the exercise first; the diagnosis is where the learning is.

Solutions 8.1.1–8.1.5

Solution 8.1.1 — Doubling a recipe

Show the diagnosis and the fix

Bug type: Logical

input() always returns a string, so cookies * 2 repeats the text ("1212") instead of computing 24. Convert the input to an int before doing arithmetic.

# Assume the user types: 12
cookies = int(input("How many cookies does the recipe make? "))
print(f"Doubled, that is {cookies * 2} cookies.")

Back to Exercise 8.1.1 · sol_8_1_1.py

Solution 8.1.2 — Average of two test scores

Show the diagnosis and the fix

Bug type: Logical

Without parentheses, score1 + score2 / 2 divides only the second score first (operator precedence), giving 125.0 instead of 85.0. Parenthesize the sum before dividing.

# Assume the user types: 80  then  90
score1 = float(input("First test score? "))
score2 = float(input("Second test score? "))
average = (score1 + score2) / 2
print(f"Your average is {average}.")

Back to Exercise 8.1.2 · sol_8_1_2.py

Solution 8.1.3 — Printing a shopping list

Show the diagnosis and the fix

Bug type: Logical

The sep argument controls what goes between the printed items; a single space produces apple banana cherry, not the comma-separated list that was wanted. Set sep=", ".

fruits = ["apple", "banana", "cherry"]
print(fruits[0], fruits[1], fruits[2], sep=", ")

Back to Exercise 8.1.3 · sol_8_1_3.py

Solution 8.1.4 — Saving a temperature reading

Show the diagnosis and the fix

Bug type: Runtime

The second open uses mode "w" again, which opens the file for writing (and erases it); calling f.read() on a write-mode file raises io.UnsupportedOperation. Open it in read mode "r" to read the contents back.

with open("reading.txt", "w", encoding="utf-8") as f:
    f.write("Tokyo,36.5\n")

with open("reading.txt", "r", encoding="utf-8") as f:
    contents = f.read()

print(contents)

Back to Exercise 8.1.4 · sol_8_1_4.py

Solution 8.1.5 — Greeting by name

Show the diagnosis and the fix

Bug type: Syntax

The f-string is missing its closing double quote, so Python never finds the end of the string and reports a syntax error. Add the closing " before the parenthesis.

# Assume the user types: Ava
name = input("What is your name? ")
print(f"Hello, {name}! Welcome aboard.")

Back to Exercise 8.1.5 · sol_8_1_5.py

results matching ""

    No results matching ""