input()

Reads a line of text typed by the user in the console.

Returns
The string typed by the user.
On this page

Example

#
Python
name = input("What's your name? ")
age = int(input("How old are you? "))

print(f"Hi {name}! In 5 years you'll be {age + 5}.")
Result
What's your name? Mia
How old are you? 14
Hi Mia! In 5 years you'll be 19.

The output shows a sample session where the user typed "Mia" and "14".

Definition and usage

#

The input() function pauses the program, shows an optional message, and waits for the user to type text and press Enter. It returns the typed text without the newline character.

The result is always a string, even if the user types a number. To do math with it, you need to convert it with int() or float(), ideally inside a try block, because the user might type anything.

input() works in programs run in a terminal. In web apps and notebooks, data is collected differently, for example through a form.

Syntax

#
Syntax
input(prompt="")

Parameters

#
  • prompt

    str, optional

    The text shown before the place to answer.

More examples

#
Safely converting to a number
Python
while True:
    text = input("Enter your score: ")
    try:
        points = int(text)
        break
    except ValueError:
        print("That's not a number, try again.")

The loop keeps asking until the user enters a valid integer.

Good practices

#
  • Always assume the user might type something unexpected. Wrap the conversion in a try block.
  • The strip() method removes accidental spaces at the start and end of the typed text.

Related entries

#

Spotted a mistake or missing an example? Write to us.