Python — User Input
input() — pause and ask
name = input("What's your name? ")
print(f"Hello, {name}!")
The program halts, shows the prompt, waits for Enter, returns everything typed as a string — always.
The conversion rule (again, because it matters)
age = input("Age? ") # "25" even if user typed digits
age + 1 # TypeError!
age = int(input("Age? ")) # convert at the door ✓
Floats:
price = float(input("Price? "))
Validation loop — never trust input
while True:
raw = input("Age: ")
if raw.isdigit():
age = int(raw)
break
print("Numbers only, please.")
Or the try/except flavor (handles negatives too):
while True:
try:
age = int(input("Age: "))
if 0 <= age <= 130:
break
print("Enter a realistic age.")
except ValueError:
print("Not a number.")
Multi-line prompts & defaults
answer = input("""Choose:
1) Start
2) Settings
> """).strip() # .strip() forgives stray spaces
if not answer:
answer = "1" # default on empty Enter
.strip() + .lower() normalize almost every messy input:
if input("Proceed? y/n ").strip().lower().startswith("y"):
start()
Multiple values in one line
x, y = input("Two numbers separated by space: ").split()
x, y = int(x), int(y)
# or list comprehension:
nums = [int(n) for n in input("Numbers: ").split()]
sum(nums)
split() without arguments splits on any run of whitespace.
Passwords — no echo
import getpass
password = getpass.getpass("Password: ") # typed chars hidden
Never input() for secrets; terminals echo everything.
Interactive menu skeleton
items = []
while True:
cmd = input("[a]dd [l]ist [q]uit > ").strip().lower()
if cmd in ("q", "quit"):
break
elif cmd in ("a", "add"):
items.append(input("New item: "))
elif cmd in ("l", "list"):
print("\n".join(items) or "(empty)")
else:
print("Unknown command")
This while-True/dispatch shape powers every console tool you'll build early on.
Gotchas: trailing
\nis NOT included in input()'s result · EOF (Ctrl+D/Ctrl+Z) raises EOFError — wrap long-running tools' input calls when piping data.
Mini Practice
- Greeter asking name + birth year → prints age.
- Bulletproof float input for a price.
- y/n confirm helper function returning bool.
- Two-number calculator reading both from one line.
- Full add/list/quit todo menu.
Next: string formatting →
Related Topics
Frequently Asked Questions about User Input
What is User Input in Python?
User Input is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn User Input?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn User Input.
Why is User Input important in Python?
User Input is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.