input in Python: asking the user to type something

input pauses the program and hands back the line typed on the keyboard, always as text, to be converted before any calculation.
5 min read
Believemy logo

Definition

A program whose values are all written into the code always gives the same result: it works out the age of a person whose birth year is fixed on line 3, and the file has to be reopened to ask somebody else. To serve several people, it needs a piece of information coming from the outside.

input is the simplest doorway for that: the function halts the program, waits for a line to be typed on the keyboard, then hands back whatever was entered. No file, no network, just the Enter key.

PYTHON
name = input("Your first name: ")   # the program stops on this line
print("Hello", name)                # it only resumes after the Enter key

# Your first name: Camille
# Hello Camille

The text inside the brackets is called the prompt. It shows up before the pause and with no line break, so that the typing appears right behind it. It stays optional, but a bare input() leaves a blinking cursor nobody knows how to fill.

The value comes back like any other function result: without a variable to hold it, it would be read and lost straight away.


What comes back is always text

Here is what surprises the most: whatever the person types, the value obtained is a string. A 25 typed on the keyboard is "25" and not the number 25. Nothing shows it on screen, since print displays both the same way, but the difference bursts open on the first calculation.

PYTHON
age = input("Your age: ")
print(age + 1)      # same as writing "25" + 1: text plus a number

# TypeError: can only concatenate str (not "int") to str

The TypeError that follows is the first error almost every beginner meets. Its message says exactly what is happening: Python can add text to text and add two numbers together, it refuses to mix the two.

That refusal is not a whim: the function reads characters without knowing what they stand for. A 25 could be a quantity, a postcode or a street number. Only the program knows the meaning of its question, so converting is its job.

Good to know

Tutorials written before 2010 read text with raw_input: the input of Python 2 evaluated the entry as code. In Python 3, input only reads, and raw_input is gone.


Converting what was typed

The conversion depends on what the program expects, and each one has its own way of breaking when the entry does not fit. Here are the four common needs.

NeedWritingIf the entry does not fit
A whole numberint(entry)Raises a ValueError
A decimal numberfloat(entry)Raises a ValueError
Plain textNothing to doCannot fail
A yes or a noentry.lower() == "yes"Simply answers false

That last row traps almost everybody, because bool looks like the obvious way to turn a yes or a no into true or false.

Warning

bool(entry) never answers the question asked: every non-empty string counts as true, "no" and "False" included. A confirmation written that way accepts anything, an explicit refusal included, and the flaw only shows up once the irreversible action has been triggered.

Only an explicit comparison is reliable, because it names the expected answer. The lower in the table serves that purpose: it brings YES, Yes and yes down to the same spelling before comparing.


Guarding against a bad entry

An entry comes from a human being, so it will be wrong one day: a word instead of a number, a comma instead of a full stop, the Enter key pressed too soon. With no precaution, int() raises an error and the program stops dead.

The guard comes in two pieces: a try around the conversion to catch the error, and a while loop that asks the question again until a usable value comes back.

PYTHON
while True:
    entry = input("Your age: ").strip()
    try:
        age = int(entry)
        break                       # a successful conversion leaves the loop
    except ValueError:
        print("Please type a whole number.")

The strip method removes the spaces that a copy and paste drags behind it: without it, a " 25 " perfectly readable on screen would make the conversion fail.

As for the except, it aims at one precise error rather than all of them. A bare except would also catch the keyboard interruption: whoever tries to leave with Ctrl+C would be asked for an age again and again, with no way out.


Frequently asked questions

Question

How can a password be asked for without showing it on screen?

Not with input, which displays everything that is typed. The getpass module, shipped with Python, does the same job while hiding the keystrokes: from getpass import getpass then secret = getpass("Password: "). The value handed back is still a string, to be converted like any other.

Question

How can several values be read on a single line?

By cutting up the string obtained with split: a, b = input().split() shares out into two variables two words separated by a space. The number of pieces must match the number of expected variables exactly, otherwise the assignment fails. It is therefore safer to check the length of the list obtained before sharing it out.

Question

The program stays stuck, is that normal?

Yes, waiting is the very principle of the function: nothing resumes before the Enter key. On a server or inside an automated script, where nobody is there to answer, that freeze becomes a flaw, and the call must give way to a command line argument. For learning, a program that asks a question and reacts to the answer is still the best starting point, and it is the one our Python course opens with.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.