Know some Python? Write your own interactive tutorial, with runnable examples and exercises, and share it with a link. Write and share your own tutorial.

Start writing

Learn Python / User Input

User Input

So far, every program has worked with values written into the code. Real programs respond to the people using them. The input() function lets your program ask a question and wait for an answer.

Asking a question

input() shows a prompt, waits for the user to type something and press Enter, then gives back what they typed.

Run this and type your answer in the Output panel:

name = input("What is your name? ")
print(f"Nice to meet you, {name}!")
Output

Step by step, this is what happens:

  1. input() prints the prompt What is your name? and the program pauses.
  2. The user types, say, Sam, and presses Enter.
  3. input() gives back the text "Sam". The Enter key isn't included.
  4. name = ... stores it, and the program carries on with the next line.

Tip: End your prompt with a space, as in "What is your name? ", so the user's answer doesn't run into the question.

The prompt is optional: plain input() waits without showing a question. It's friendlier to always tell people what to type, though.

Input is always a string

Whatever the user types, input() returns a string, even if it looks like a number. Run this and type 5:

answer = input("Type a number: ")
print(type(answer))
print(answer * 3)
Output

You got 555, not 15, because "5" * 3 repeats the text. To do maths, convert the input first:

answer = input("Type a number: ")
number = int(answer)
print(number * 3)
Output

You can convert in one step by wrapping input() in int() or float(). Python works from the inside out: input() runs first and gives back text, then int() or float() converts that text to a number:

age = int(input("How old are you? "))
height = float(input("How tall are you in metres? "))

print(f"Next year you will be {age + 1}.")
print(f"That's {height * 100:.0f} cm.")
Output

Use int() for whole numbers and float() when the user might type a decimal. (:.0f shows the number with no decimal places, so 1.75 metres prints as 175 cm.)

int() and float() ignore spaces around the number, so " 42 " converts fine.

When the input isn't a number

If the user types something that can't be converted, Python raises a ValueError. Run this and type hello:

number = int(input("Type a whole number: "))
print(number * 2)
Output

The same thing happens if the user just presses Enter without typing anything: input() gives back an empty string "", and int("") is a ValueError too.

You'll learn how to handle errors like this gracefully in the Errors and Exceptions lesson. For now, just know why it happens.

Going deeper: Why int("3.5") fails optional

int() can turn a decimal number into a whole number, but it can't turn decimal text into one. The text "3.5" isn't a whole number, so int() refuses:

# a float: works, gives 3
print(int(3.5))

# decimal text: ValueError
print(int("3.5"))
Output

If the user might type a decimal but you need a whole number, convert to float first, then to int:

answer = input("How many hours did you work? ")
hours = int(float(answer))
print(f"Full hours: {hours}")
Output

Remember that int() cuts off the decimals rather than rounding. Use round(float(answer)) if you want 3.7 to become 4.

Cleaning up text input

People add stray spaces and capital letters. Combine input() with the string methods from the last lesson to tidy things up:

color = input("What's your favourite colour? ").strip().lower()
print(f"You chose: {color}")
Output

Try typing BLUE. input() gives back the text exactly as typed, strip() removes the spaces at both ends, and lower() makes it blue. Cleaning input like this means "Blue", "BLUE" and " blue" are all treated the same.

Going deeper: Reading several values from one line optional

split() from the String Methods lesson lets you read several values the user types on one line. Run this and type something like 3 4:

line = input("Enter width and height separated by a space: ")
parts = line.split()

width = int(parts[0])
height = int(parts[1])
print(f"Area: {width * height}")
Output

Putting it together: a tip calculator

bill = float(input("Bill amount: "))
tip_percent = int(input("Tip percentage (e.g. 15): "))
people = int(input("Number of people: "))

tip = bill * tip_percent / 100
total = bill + tip
each = total / people

print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Each person pays: {each:.2f}")
Output

Try a bill of 40, a tip of 15 and 2 people:

Line Calculation Value
tip = bill * tip_percent / 100 40.0 * 15 / 100 6.0
total = bill + tip 40.0 + 6.0 46.0
each = total / people 46.0 / 2 23.0

Each answer is converted to the right type as soon as it's read: float for money, which can have cents, and int for counts. After that, the rest of the program is ordinary maths.

Exercises

These exercises are interactive. Your program asks questions, and you type the answers in the Output panel.

Exercise 1: Personal greeting

Ask the user for their name and their city, then print Hello <name> from <city>!

# Ask for name and city, then greet the user
Output

Exercise 2: Add two numbers

Ask for two whole numbers and print their sum. If the user types 4 and 6, it should print 4 + 6 = 10.

# Ask for two numbers and print their sum
Output

Exercise 3: Temperature converter

Ask for a temperature in Celsius (it may have decimals) and print it in Fahrenheit using F = C × 9 / 5 + 32. For 25, print 25.0°C is 77.0°F.

# Convert Celsius to Fahrenheit
Output

Exercise 4: Fix the program

This program is meant to tell the user how old they'll be in 10 years, but it crashes. Run it, read the error, and fix it.

age = input("How old are you? ")
print(f"In 10 years you will be {age + 10}.")
Output

Summary

  • input("prompt ") waits for the user and returns what they typed.
  • The result is always a string. Convert it with int() or float() before doing maths.
  • Converting text that isn't a number raises a ValueError.
  • Chain .strip() and .lower() to clean up text input.
  • split() lets you read several values from one line.

Share this tutorial

Know something worth teaching? Write your own tutorial with runnable examples and share it.