User Input

Ask for user input with Python's input() in your browser: convert answers to numbers, ask again after a bad answer and read several values.

Python
name = input("What is your name? ")
print("Hello, " + name + "!")

input() is the built-in Python function for asking the person running a program to type something. It shows a prompt, waits for an answer and returns what was typed as a string. Beginners use it for first programs such as a quiz or a calculator, and scripts use it to ask for a file name or a menu choice. On this page it runs in your browser, so you can try it without installing anything. Run the example first, then paste any snippet below into a new cell to try it.

What the example does

input("What is your name? ") shows its argument as a prompt and returns the answer. In a terminal, the prompt is printed and you type after it. On this page, the browser opens a dialog with the prompt and a text box instead, and the code waits until you click OK or Cancel. The answer is always a string, so "Hello, " + name + "!" joins three strings, and print() shows the result, such as Hello, Ada!. The prompt and your answer do not appear in the output, only what the code prints.

Convert the answer to a number

Digits typed into input() still arrive as a string. Convert them with int() or float() before doing math:

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

price = float(input("Price in dollars: "))
print(f"With 8% tax: {price * 1.08:.2f}")

An answer that is not a number, such as ten, stops the code with ValueError: invalid literal for int() with base 10: 'ten'.

Ask again until the answer is valid

A while loop keeps asking until an answer passes every check. try and except ValueError catch answers that are not whole numbers, and break leaves the loop:

while True:
    answer = input("Pick a number from 1 to 10: ")
    try:
        number = int(answer)
    except ValueError:
        print(repr(answer), "is not a whole number")
        continue
    if 1 <= number <= 10:
        break
    print(number, "is out of range")

print("You picked", number)

Read several values from one line

split() breaks an answer into a list of parts, so one prompt can collect several values. With no argument it splits on spaces, and with "," it splits on commas:

words = input("Numbers separated by spaces: ").split()
values = [float(word) for word in words]
print(len(values), "numbers, total", sum(values))

name, city = input("Name and city, separated by a comma: ").split(",")
print(name.strip(), "lives in", city.strip())

Unpacking into name, city needs exactly two parts. An answer with no comma, or with two, raises ValueError.

Use a default for an empty answer

Here, clicking Cancel returns an empty string, the same as clicking OK with the box empty. An empty string counts as false, so or can supply a default. strip() removes stray spaces and lower() makes a yes/no check ignore case:

name = input("Your name (leave empty to skip): ").strip() or "friend"
print(f"Hello, {name}!")

reply = input("Continue? [y/n] ").strip().lower()
print("Continuing" if reply in ("y", "yes") else "Stopped")

Good to know

  • Each call opens its own dialog. For more than a few values, put them in a list in the code or read them from a file, as in the Files example.
  • Outside the browser, input() raises EOFError when its input runs out, for example when a script's input comes from an empty file. Here, Cancel returns "" instead, so check for an empty string.
  • For passwords and API keys, getpass is the usual choice, because it hides what you type in a terminal. On this page it opens the same dialog, so the text stays visible while you type.