Programs become interesting when they respond to the person using them: a quiz that checks your answer, a calculator that uses your numbers, a game that asks your name. In Python, the input() function gets what the user types.
There's one catch that trips up almost every beginner: input() always gives you text, even when the user types a number. This guide shows how input() works, how to convert between types, how to read several values at once, and how to stop your program crashing when someone types the wrong thing.
How input() works
name = input("What's your name? ")
print(f"Hello, {name}!")
- Python shows the message (the prompt) and pauses.
- The user types something and presses Enter.
input()returns what they typed, as a string, and=stores it inname.
End the prompt with a space so the answer doesn't touch the question.
The catch: input() returns a string
age = input("Age: ") # the user types 20
print(type(age)) # <class 'str'>
print(age + 1) # TypeError: can only concatenate str (not "int") to str
print(age * 3) # 202020: repeats the text!
To Python, "20" with quotes is two characters, not a number. You must convert it first.
Converting between types
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Whole number | int("42") | 42 |
float() | Decimal number | float("3.5") | 3.5 |
str() | Text | str(99) | '99' |
bool() | True or False | bool("") | False |
Wrap input() in the conversion you need:
age = int(input("Age: "))
height = float(input("Height in metres: "))
print(f"Next year you'll be {age + 1}.")
A few rules worth knowing:
int("3.5")fails with aValueError. Usefloat()for decimals, orint(float("3.5"))to get3.int(3.9)gives3: it cuts off the decimals, it doesn't round. Useround(3.9)to get4.int(" 42 ")works: spaces at the ends are ignored.bool("False")isTrue! Any non-empty string counts as true. To check a yes/no answer, compare the text instead.
Python converts some types for you
When you mix an int and a float in maths, Python converts the int automatically. This is called implicit conversion:
5 + 2.0 # 7.0
True + 1 # 2: True counts as 1, False as 0
Python won't convert between text and numbers on its own, because it can't guess what you meant: "5" + 5 could mean "55" or 10. You do that explicitly with int() or str().
Cleaning up text answers
People type extra spaces and random capital letters. Clean the answer before checking it:
answer = input("Do you want to continue? (yes/no) ").strip().lower()
if answer in ("yes", "y"):
print("Continuing...")
else:
print("Goodbye!")
strip() removes spaces at the ends and lower() makes "YES" and "Yes" both "yes".
Reading several values on one line
split() breaks the text at spaces, and map() converts every piece:
a, b = input("Enter two numbers: ").split() # the user types 4 9
print(int(a) + int(b)) # 13
x, y = map(int, input("Enter two numbers: ").split())
print(x * y) # 36
For a whole list of numbers:
marks = list(map(int, input("Marks: ").split())) # 72 88 95
print(sum(marks) / len(marks)) # 85.0
This pattern is common in coding tests and competitive programming. If the number of values typed doesn't match the number of variables, Python raises a ValueError.
Validating input so your program doesn't crash
If someone types twenty where you expected a number, int() raises a ValueError and the program stops. Catch the error with try and except, and keep asking until the answer is valid:
while True:
try:
age = int(input("Age: "))
break # valid: leave the loop
except ValueError:
print("Please type a whole number, like 21.")
print(f"Thanks! You are {age}.")
You can check the range too:
while True:
try:
rating = int(input("Rate us from 1 to 5: "))
except ValueError:
print("That's not a number.")
continue
if 1 <= rating <= 5:
break
print("Please choose 1, 2, 3, 4 or 5.")
"42".isdigit() is another quick check, but it returns False for negative numbers and decimals, so try/except is more reliable. Python file handling covers try and except in more depth.
Key takeaways
input()always returns a string; convert it withint()orfloat()before doing maths.int()cuts off decimals and fails on text like"3.5"or"abc".- Clean text answers with
.strip().lower()before comparing them. - Use
split()andmap()to read several numbers from one line. - Wrap conversions in
try/except ValueErrorinside a loop to handle bad input.
Practice
- Ask for the length and width of a room in metres and print its area.
Show the answer
length = float(input("Length (m): "))
width = float(input("Width (m): "))
print(f"Area: {length * width:.2f} square metres")
- Ask for three marks on one line, separated by spaces, and print the average.
Show the answer
a, b, c = map(int, input("Three marks: ").split())
print(f"Average: {(a + b + c) / 3:.1f}")
- What does each line print?
print(int("7") + 3)
print("7" + "3")
print(int(9.99))
print(float("2"))
print(bool("0"))
Show the answer
10, 73, 9, 2.0 and True. The last one surprises people: "0" is a non-empty string, so it's true. bool(0), with the number, is False.
- Ask for a PIN and keep asking until the user types exactly 4 digits.
Show the answer
while True:
pin = input("4-digit PIN: ").strip()
if len(pin) == 4 and pin.isdigit():
break
print("The PIN must be exactly 4 digits.")
print("PIN saved.")
Keep a PIN as a string: as a number, 0042 would lose its leading zeros.
Interview questions
What does input() return in Python 3?
Always a str. In Python 2, input() evaluated what the user typed as code, which was unsafe; Python 3's input() behaves like Python 2's raw_input().
What is the difference between implicit and explicit type conversion?
Implicit conversion is done automatically by Python, such as turning an int into a float in 5 + 2.0. Explicit conversion (type casting) is done by the programmer with functions like int(), float() and str().
How do you read multiple integers from one line of input?
a, b = map(int, input().split()) for a fixed number of values, or nums = list(map(int, input().split())) for any number. split() breaks the line at whitespace and map(int, ...) converts each piece.
What happens when int() gets an invalid string?
It raises a ValueError, for example invalid literal for int() with base 10: 'abc'. Catch it with try/except ValueError to handle bad input.
What to learn next
- Finish the basics with Python comments and readable code.
- Use the input you collect to make decisions with Python if, elif and else.