Python Tutorial › Getting Started › User Input

Python User Input

BeginnerLesson 7 of 478 min read7 runnable examples

input() pauses your program and waits for the user to type something and press Enter. It is the simplest way to make a program interactive, and it is used in many practice programs.

Advertisement
In this lesson
  • Read text with input()
  • Convert input to numbers
  • Read several values from one line
  • Handle input that is not a number

Read text with input()

input() shows an optional prompt, waits for the user and returns what they typed as a string.

Python
name = input("What is your name? ")print("Hello,", name)
Outputtyped input: Asha
What is your name? Asha
Hello, Asha
Note

When you press Try it and Run on this site, your browser shows a small box for each input(). The recorded output above shows a run where the user typed Asha, exactly as it appears in a terminal.

input() always returns a string

Even if the user types digits, you get a string. Adding two strings joins them instead of adding numbers:

Python
a = input("First number: ")b = input("Second number: ")print(a + b)print(type(a))
Outputtyped input: 5, 7
First number: 5
Second number: 7
57
<class 'str'>

Convert input to a number

Wrap input() in int() for whole numbers or float() for decimals.

Python
qty = int(input("Quantity: "))price = float(input("Price: "))print("Total:", qty * price)
Outputtyped input: 5, 7.5
Quantity: 5
Price: 7.5
Total: 37.5
You wantUseExample inputResult
Textinput()pune'pune'
Whole numberint(input())4242
Decimal numberfloat(input())3.753.75

Several values on one line

split() breaks a string on spaces and returns a list. Combine it with map() to convert every part:

Python
numbers = input("Enter numbers separated by spaces: ").split()print(numbers) values = list(map(int, numbers))print(sum(values))
Outputtyped input: 10 20 30
Enter numbers separated by spaces: 10 20 30
['10', '20', '30']
60

Unpack directly into variables when you know how many values to expect:

Python
width, height = map(int, input("Width and height: ").split())print("Pixels:", width * height)
Outputtyped input: 1920 1080
Width and height: 1920 1080
Pixels: 2073600

Handle invalid input

If the user types abc, int() cannot convert it and raises a ValueError:

Python
age = int(input("Age: "))
Outputtyped input: abc
Age: abc
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    age = int(input("Age: "))
ValueError: invalid literal for int() with base 10: 'abc'

Catch the error with try / except and ask again. The Exception Handling lesson explains this pattern fully.

Python
while True:    text = input("Age: ")    try:        age = int(text)    except ValueError:        print(f"{text!r} is not a whole number, try again")        continue    if age < 0:        print("Age cannot be negative")        continue    break print("Age saved:", age)
Outputtyped input: abc, -3, 29
Age: abc
'abc' is not a whole number, try again
Age: -3
Age cannot be negative
Age: 29
Age saved: 29
Tip

text.strip() removes spaces the user typed by accident before or after the value. Use it before comparing input, for example input().strip().lower() == "yes".

Check your understanding

Quick quiz

1. The user types 8. What is the type of input()‘s result?

2. What does "3" + "4" give?

3. Which reads two whole numbers typed on one line as 4 9?

Exercise: rectangle calculator

Ask for the width and height on one line and print the area and the perimeter.

Input
4 6
Expected output
Width and height: 4 6
Area: 24
Perimeter: 20
Hint 1

split() then map(int, ...) gives you two numbers.

Hint 2

Perimeter is 2 * (width + height).

Program Practice

Many basic programs read their values with input(). Try changing a solution to ask the user instead of using fixed values.

Python input FAQ

How do I take integer input in Python?

Wrap input() in int(): n = int(input("Enter a number: ")). Use float() for decimal numbers.

How do I take multiple inputs in one line?

Use split(): a, b = input().split(). Add map(int, ...) to convert them to numbers.

What happens if the user enters text when I expect a number?

int() raises ValueError. Catch it with try / except ValueError and ask again.

Is raw_input() still available?

No. raw_input() was Python 2. In Python 3, input() does the same job and always returns a string.

Leave a Comment