input() lets your program ask the user a question and wait for an answer. It is how simple games, quizzes and calculators talk to the person using them.
ASKING A QUESTION
name = input("What is your name? ")
print("Hi,", name)
The program stops at input(), shows the question, and waits until the user presses Enter. Whatever they typed is stored in name. If they type Mia, it prints Hi, Mia.
INPUT IS ALWAYS TEXT
This is the number one surprise: even if the user types 5, input() gives you the string "5", not the number 5.
answer = "5"
print(answer + answer)
print(int(answer) + int(answer))55
10
Convert it with int() for whole numbers or float() for decimals before doing math.
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
WHEN THE USER TYPES SOMETHING ELSE
int("hello") crashes with a ValueError. Catch it so your program can ask again instead of stopping:
def to_number(text):
try:
return int(text)
except ValueError:
return None
print(to_number("42"))
print(to_number("forty-two"))42
None
CLEANING UP ANSWERS
reply = " YES "
if reply.strip().lower() == "yes":
print("Let's play!")Let's play!
Users add spaces and capital letters. strip() and lower() make the comparison work anyway.
A TINY GUESSING GAME
secret = 7
guess = None
while guess != secret:
guess = int(input("Guess a number from 1 to 10: "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print("You got it!")
a = "3"
b = 4
print(int(a) * b)int(a) turns the text "3" into the number 3, and 3 * 4 = 12. Without int(), "3" * 4 would repeat the text: 3333.COMMON BEGINNER MISTAKES
input() + 1 fails because input is text. Convert first.input() == 5 is always False. Compare with "5" or convert to int.PRACTICE IT, DON'T JUST READ IT
Snekcade lets you practise this logic with real Python on your phone, one short level at a time. The first worlds are free.
PLAY PRINT PLAINS ▸FAQ
Why does input() return a string in Python?
Everything typed on a keyboard is text, so input() always returns a string. Convert it with int() or float() to do math.
How do I get a number from input()?
Wrap it: age = int(input("Age? ")). Use float() for decimals.
How do I handle it when the user types letters instead of a number?
Put int() inside try and catch ValueError, then ask again.