Python - User Input
Overview
Estimated time: 10–20 minutes
Read input from users via the console and validate it safely.
Learning Objectives
- Use
input()
to read strings from stdin. - Parse numbers with
int()
/float()
and handle exceptions. - Prompt clearly and loop until valid input is received.
Prerequisites
Reading input
name = input("Your name: ")
print(f"Hello, {name}!")
Validation with try/except
while True:
raw = input("Enter an integer: ")
try:
n = int(raw)
break
except ValueError:
print("Invalid integer, try again.")
print(n)
Common Pitfalls
- Assuming input is always valid; always handle
ValueError
. - Forgetting to strip whitespace: use
.strip()
.
Checks for Understanding
- What does
input()
return? - How do you handle non-integer input when parsing?
Show answers
- A string.
- Wrap
int(raw)
in atry/except ValueError
.
Exercises
- Prompt for a float and print its square rounded to 2 decimals.
- Read a comma-separated list of numbers and print their sum.