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.
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.
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'.
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)
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.
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")
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.