Python User Input
Interactive programs ask the user for information: their name, a menu choice, a number to calculate with. In a terminal program, Python's built-in input() function does this.
How input() works
input() optionally prints a prompt, waits until the user types something and presses Enter, then returns what they typed as a string:
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")A run in the terminal looks like this (the user typed Linh):
python3 greet.pyWhat is your name? Linh
Nice to meet you, Linh!
Note: The playgrounds on this site run without a keyboard connection to the program, so they can't pause and wait for typing. In the runnable examples below, a fixed string stands in for "what the user typed". Copy the code to your computer and replace those strings with
input(...)calls to make them truly interactive.
Input is always a string
Even if the user types 42, input() returns the string "42". Convert it before doing maths:
age = int(input("Age: "))
print("Next year you'll be", age + 1)Here's the same logic with the typed text simulated:
typed = "42" # pretend the user typed 42
print(typed + "1") # string concatenation, not maths!
age = int(typed)
print(age + 1)421
43
| You want | Convert with |
|---|---|
| a whole number | int(text) |
| a decimal number | float(text) |
| yes/no | text.strip().lower() in ("y", "yes") |
| several values | text.split() |
Cleaning up input
People add stray spaces and use random capitalisation. Normalise input before using it:
typed = " YeS "
answer = typed.strip().lower()
if answer in ("y", "yes"):
print("Confirmed")
else:
print("Cancelled")
typed = "3 7 12"
numbers = [int(part) for part in typed.split()]
print(numbers, "sum =", sum(numbers))Confirmed
[3, 7, 12] sum = 22
Validating input
Users make typos. A robust program keeps asking until it gets a valid answer. The usual pattern is a while True loop with try/except:
while True:
text = input("Enter your age: ")
try:
age = int(text)
except ValueError:
print("Please enter a whole number.")
continue
if 0 <= age <= 120:
break
print("That doesn't look like a real age.")
print("Thanks! Age recorded:", age)To test this logic without a keyboard, we can feed it a list of answers. Moving the loop into a function that takes the answers as a parameter is also a good habit — it makes the code testable:
def ask_age(answers):
for text in answers:
print(f"Enter your age: {text}")
try:
age = int(text)
except ValueError:
print("Please enter a whole number.")
continue
if 0 <= age <= 120:
return age
print("That doesn't look like a real age.")
return None
simulated = ["twenty", "-5", "250", "34"]
print("Thanks! Age recorded:", ask_age(simulated))Enter your age: twenty
Please enter a whole number.
Enter your age: -5
That doesn't look like a real age.
Enter your age: 250
That doesn't look like a real age.
Enter your age: 34
Thanks! Age recorded: 34
A small menu program
Menus are another classic input pattern. Here, the choices are simulated with a list:
def run_menu(choices):
balance = 100
for choice in choices:
print("1) Balance 2) Deposit 50 3) Quit >", choice)
if choice == "1":
print("Balance:", balance)
elif choice == "2":
balance += 50
print("Deposited.")
elif choice == "3":
print("Bye!")
break
else:
print("Unknown option.")
run_menu(["1", "2", "9", "1", "3"])1) Balance 2) Deposit 50 3) Quit > 1
Balance: 100
1) Balance 2) Deposit 50 3) Quit > 2
Deposited.
1) Balance 2) Deposit 50 3) Quit > 9
Unknown option.
1) Balance 2) Deposit 50 3) Quit > 1
Balance: 150
1) Balance 2) Deposit 50 3) Quit > 3
Bye!
Other ways to get input
| Source | Tool |
|---|---|
| Command-line arguments | sys.argv, or the argparse module |
| Passwords (hidden typing) | getpass.getpass() |
| Files | open() — see File Handling |
| Environment variables | os.environ |
Tip: If the input stream ends (for example the user presses Ctrl+D, or the program is fed from an empty file),
input()raisesEOFError. Long-running interactive tools catch it to exit cleanly.
Test yourself
What type does input() return?
- int
- Whatever the user typed
- str
- bytes
The user types 5 for x = input(). What is x * 2?
- 10
- "55"
- "10"
- TypeError
Which exception does int("abc") raise when validating input?
- TypeError
- ValueError
- InputError
- SyntaxError