CodeMIRAI
0 XP

Getting input from the user

2 min read 6 runnable examples Quiz included

The input() function pauses your program and waits for the user to type a line of text. Whatever they type is returned as a string.

Reading a line

Python
name = input("What's your name? ")
print("Nice to meet you,", name)

The text inside input() is the prompt shown to the user. It is optional, but it tells people what to type.

input() always returns a string

Even if the user types a number, you get text:

Python
age = input("How old are you? ")
print(type(age))
print(age + 1)

That TypeError is the classic beginner bug. Convert the input first:

Python
age = int(input("How old are you? "))
print("Next year you will be", age + 1)

Several inputs

Each input() reads one line:

Python
a = int(input("First number: "))
b = int(input("Second number: "))
print(a, "+", b, "=", a + b)

Several values on one line

When values arrive on one line, separated by spaces, use split() to break the line apart:

Python
parts = input().split()
print(parts)

numbers = [int(p) for p in parts]
print(sum(numbers))

A shorter way for a fixed number of values:

Python
width, height = map(int, input().split())
print("Pixels:", width * height)

map(int, ...) applies int() to every piece. This pattern appears in almost every coding challenge.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.