How to Get User Input in Python with input()
Learn how Python's input() function works, why it always returns a string, and how to convert numbers, handle bad input and read several values at once.
On this page
Most useful programs need information from the person using them: a name, an answer, a number to work with. In Python, the tool for that is the built-in input() function. This guide covers how it works, the one surprise that trips up almost every beginner, and how to handle answers you did not expect.
What input() does
name = input("What is your name? ")
print("Hello,", name)If you type Ada and press Enter, you see:
What is your name? Ada
Hello, AdaThree things happen when Python reaches input():
- It shows the text in the brackets, called the prompt.
- It pauses the program and waits for the user to type something and press Enter.
- It gives back whatever was typed, without the Enter, so you can store it in a variable.
End your prompt with a space. Without it, the answer is typed right up against the question: What is your name?Ada.
input() always gives you a string
This is the part that catches everyone out. Whatever the user types, input() returns it as text, even if it looks like a number:
age = input("How old are you? ")
print(age + 1)How old are you? 12
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(age + 1)
~~~~^~~
TypeError: can only concatenate str (not "int") to strThe variable age holds the text "12", not the number 12. Python will not add a number to a piece of text, so it stops with a TypeError.
Turning input into numbers
Wrap input() in int() to turn the answer into a whole number:
age = int(input("How old are you? "))
print("Next year you will be", age + 1)How old are you? 12
Next year you will be 13Use float() instead when the answer can have a decimal point, such as a price or a measurement:
price = float(input("Price: "))
print("With 13% tax:", round(price * 1.13, 2))Price: 20
With 13% tax: 22.6When the user types something unexpected
int() only works on text that looks like a whole number. If the user types twelve, Python stops with a ValueError. You can catch that with try and except and simply ask again:
while True:
text = input("Enter a whole number: ")
try:
number = int(text)
break
except ValueError:
print("That is not a whole number. Try again.")
print("You entered", number)Enter a whole number: twelve
That is not a whole number. Try again.
Enter a whole number: 12
You entered 12The loop keeps going until int() succeeds. Then break leaves the loop and the program carries on.
Reading several values at once
Sometimes you want two or more values on one line. The .split() method breaks the text wherever there are spaces:
first, second = input("Enter two numbers: ").split()
total = int(first) + int(second)
print("Total:", total)Enter two numbers: 5 7
Total: 12For any number of values, convert each piece in a list comprehension:
numbers = [int(n) for n in input("Numbers: ").split()]
print("Sum:", sum(numbers))Numbers: 3 4 5
Sum: 12Cleaning up text answers
People type answers in all sorts of ways: yes, Yes, YES . Use .strip() to remove spaces at either end and .lower() to make everything lowercase, and you only need to check one version:
answer = input("Do you like Python? (yes/no) ").strip().lower()
if answer == "yes":
print("Great!")
else:
print("Give it time.")Do you like Python? (yes/no) YES
Great!Putting it together: a guessing game
Here is a small game that uses everything above. It keeps asking until you find the secret number:
secret = 7
guesses = 0
while True:
guess = int(input("Guess a number from 1 to 10: "))
guesses = guesses + 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print("Got it in", guesses, "guesses!")
breakGuess a number from 1 to 10: 5
Too low
Guess a number from 1 to 10: 9
Too high
Guess a number from 1 to 10: 7
Got it in 3 guesses!To make the secret different every time, add import random at the top and use secret = random.randint(1, 10).
Common mistakes
- Doing maths on the raw answer. Convert it first with
int()orfloat(). - No space at the end of the prompt. The answer ends up squashed against the question.
- Not expecting bad input. Real users mistype. Use
tryandexceptfor anything you convert. - Comparing without cleaning up.
"Yes" == "yes"isFalse, so use.strip().lower()first.
Try it yourself
Many online Python editors cannot run input() at all. In the PythonExecutor playground it works like it does on your own computer: press Run, and when your program asks a question, type the answer straight into the terminal. Paste in the guessing game above and see if you can win in three guesses.
By PythonExecutor Team