Lesson 7 of 30 · Working With Data
Getting User Input
Make your Python programs interactive with input(). Ask the user questions, store their answers and use them in your output.
- 6 min read
- Beginner
- Reviewed
- How to ask the user a question with input()
- How to store the answer in a variable and use it
- Why input() always gives you a string
Programs that listen
So far your programs have always done the same thing. Real programs react to the person using them. The input() function pauses the program, waits for the user to type something and gives you what they typed.
name = input("What is your name? ")
print(f"Hello, {name}!")How it works, step by step
Look at this line:
name = input("What is your name? ")- Python shows the text inside the brackets. This text is called the prompt.
- The program waits for the user to type and press Enter.
- Whatever they typed is stored in the variable
name.
Asking several questions
Each input() reads one line. The Input box below has two lines, one for each question.
name = input("What is your name? ")
city = input("Where do you live? ")
print(f"{name} lives in {city}.")input() always returns a string
This is the most important thing to remember about input(). Even when the user types a number, Python stores it as text.
age = input("How old are you? ")
print(age)
print(type(age))The type is str, not int. That matters as soon as you try to do maths.
age = input("How old are you? ")
print(age + age)The output is 2525, not 50. With strings, + joins instead of adding. And age + 1 would stop the program with a TypeError, because Python cannot add a number to text.
The fix is to convert the text into a number, which is the subject of the next lesson.
Common mistakes
The program already asks for a favourite food. Add one line that replies I like pizza too!, using the food variable so that it works for any food.
food = input("What is your favourite food? ")
# Print a reply so the last line of output is exactly:
# I like pizza too!
The user types 7 when this runs: x = input('Number: '). What is the type of x?
Summary
input()asks the user a question and returns their answer.- Store the answer in a variable to use it later.
- The value returned by
input()is always a string. - To do maths with it, you must convert it first.
Next: converting between types.
Finished reading? Tick it off to track your progress.