Programs that talk to the user
Be able to read text in, convert it to a number and answer — and handle bad input.
Prerequisites
- CPython — the basicsrequired
Intuition
input() reads one line from the user and always gives a string — even if the user types digits.
age = input("How old are you? ")
print(age + 1) # TypeError! age is "12", not 12
You have to convert: int(age). But if the user types «twelve», int() crashes. Real programs have to survive that.
Code
def read_number(question, attempts=3):
for _ in range(attempts):
answer = input(question).strip().replace(",", ".")
try:
return float(answer)
except ValueError:
print(f"'{answer}' is not a number. Try again.")
raise ValueError("too many invalid attempts")
age = read_number("How old are you? ")
print(f"Next year you turn {age + 1:.0f}")
Three things that make this function good:
.strip()removes spaces the user typed by accident..replace(",", ".")accepts the Swedish decimal comma.try/exceptcatches the error and asks again instead of crashing.
Always test your program with: an ordinary value, an empty answer, text instead of a number, and a negative number. Those four reveal the bugs.
Mastery means
- Reads text in and converts it to a number
- Handles invalid input without the program crashing
Sign in to do the exercises and build your mastery up.