Why does input() return a string in Python?
Short answer
input() always returns a str, even when the user types digits. Wrap it in int() or float() immediately, or arithmetic will fail with a TypeError.
Python has no way to know whether 42 should be a number, a house number, or a product code. Rather than guess, it hands you exactly what was typed.
age = input("How old are you? ") # user types 30
print(age + 10) # TypeError: can only concatenate strConvert at the boundary — the same line the value arrives on:
age = int(input("How old are you? "))
print(f"In ten years you will be {age + 10}.")#Handle input that is not a number
int() raises ValueError on anything it cannot parse. Wrap it:
while True:
try:
age = int(input("How old are you? "))
break
except ValueError:
print("Please enter a whole number.")That loop is the standard shape for any prompt that must produce a number.
#The subtle one
int("3.7") also fails. int parses integers, not decimals. If you might get either, use float() first and round or truncate afterwards.