input() is Python’s standard way to read a line from the keyboard. It shows an optional prompt, waits until the user presses Enter, and returns what they typed as a str.
If you need a number, convert with int() or float(). If the user might enter invalid text, catch ValueError with try/except—or loop until the input is valid.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Python input() quick reference
| Task | Use |
|---|---|
| Take string input | input("Enter your name: ") |
| Take integer input | int(input("Enter your age: ")) |
| Take float input | float(input("Enter price: ")) |
| Remove spaces | input().strip() |
| Normalize yes/no input | input().strip().lower() |
| Take multiple values | input().split() |
| Validate numeric input | try/except ValueError |
| Keep asking until valid | while True with try/except |
| Async-compatible input | asyncio.to_thread() or aioconsole |
| Hide password input | getpass.getpass() |
Basic syntax of input()
input([prompt])prompt— optional string shown before input (add a trailing space so the cursor is not glued to the text).- Behavior — pauses the program until Enter.
- Return value — always
str(including empty string""if the user presses Enter with no text).
See the official input() docs.
Take string input in Python
name = input("Enter your name: ")
print(f"Hello, {name}!")End prompts with a space or colon plus space so output reads cleanly in the terminal.
input() always returns a string
This is the most common beginner surprise—and it matches quiz-style “age + 1” questions.
age = input("Enter your age: ")
print(type(age))
try:
print(age + 1)
except TypeError as e:
print(e)You should see <class 'str'> and a TypeError about concatenating str and int. The user typed 25, but Python stored "25", not 25.
Take integer input using int(input())
age = int(input("Enter your age: "))
print("Next year, you will be " + str(age + 1) + " years old!")Why this works:
input()returns text.int()converts it to an integer.age + 1is numeric addition.str()converts the result back for string concatenation (or use an f-string:f"Next year, you will be {age + 1} years old!").
Use int(input(...)) for age, counts, menu numbers, and quantities.
What happens if the user enters a non-numeric value?
age = int(input("Enter your age: "))If the user types abc, Python raises ValueError and the program stops unless you handle it:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a whole number.")That directly answers “what if age is not numeric?”—you need validation, not bare int(input()) in production-style code. The same try / except pattern applies when reading configuration from files.
Validate numeric user input
Loop until input is valid, then optionally check a range:
while True:
raw = input("Enter your age: ").strip()
try:
age = int(raw)
except ValueError:
print("That is not a valid integer.")
continue
if age <= 0:
print("Age must be greater than 0.")
continue
break
print(f"You entered {age}.")Same pattern works for menu choices (1–4), quantities, and any bounded integer.
Take float input in Python
price = float(input("Enter price: "))
print(f"Price: {price:.2f}")Use float() for decimals (price, height, weight, percentages). Non-numeric input still raises ValueError—wrap with try/except the same way as integers.
Take multiple inputs in one line
Space-separated:
parts = input("Enter two numbers: ").split()
a, b = int(parts[0]), int(parts[1])
print(a + b)Comma-separated:
parts = [p.strip() for p in input("Enter values (comma-separated): ").split(",")]
print(parts)split() returns strings—convert each part with int() or float() when needed.
Clean and normalize user input
answer = input("Continue? (yes/no): ").strip().lower()
if answer in ("yes", "y"):
print("Continuing.")
elif answer in ("no", "n"):
print("Stopping.")
else:
print("Unknown response.")strip() removes accidental leading/trailing spaces. lower() makes Yes, YES, and yes compare consistently.
Use input() with conditional statements
Interactive programs often combine input() with if/elif/else:
choice = input("What do you need? (list/set/dict/tuple): ").strip().lower()
if choice == "list":
print("Use a list for ordered, changeable items.")
elif choice == "set":
print("Use a set for unique items.")
elif choice == "dict":
print("Use a dict for key-value data.")
elif choice == "tuple":
print("Use a tuple for a fixed collection.")
else:
print("Unknown choice.")One prompt, one branch—typical “interactive input python” flow without building a full application around it.
Python async input with asyncio
input() is blocking. Calling it directly inside async def blocks the entire event loop—other coroutines cannot run while waiting for the keyboard.
Stdlib approach — run blocking input() in a thread:
import asyncio
async def ask_name() -> str:
return await asyncio.to_thread(input, "Enter your name: ")
async def main():
name = await ask_name()
print(f"Hello, {name}!")
asyncio.run(main())Alternative: loop.run_in_executor(None, input, "prompt") on older patterns.
Third-party: aioconsole provides async-friendly ainput() / aprint() when you want an API designed for asyncio.
Do not assume async def + input() alone is non-blocking—it is not.
input() vs sys.argv vs argparse
| Method | Use when |
|---|---|
input() |
Ask the user interactively while the program runs |
sys.argv |
Read simple command-line arguments |
argparse |
Build a CLI with options, help, and validation |
| File input | Read prepared data from a file |
For batch data already on disk, prefer read and write CSV in Python or write to file workflows instead of typing rows at the prompt.
For script arguments at launch, see Python argparse. input() is for mid-run prompts in the terminal.
Password input in Python
Do not use input() for passwords—characters appear on screen. Use getpass.getpass() from the standard library:
import getpass
password = getpass.getpass("Password: ")For masked input with asterisks and platform notes, see Python password input with asterisks.
Mistakes to avoid with Python input()
- Forgetting
input()always returns astr. - Doing
age + 1withoutint()conversion. - Ignoring
ValueErroronint(input())/float(input()). - Using
eval(input())—never execute arbitrary user text as code. - Calling blocking
input()directly insideasync defwithoutto_thread/ executor. - Using
input()for passwords. - Comparing yes/no answers without
strip().lower(). - Building shell commands from raw user strings—avoid
os.system(user_text); if you must run subprocesses, use Python subprocess withsubprocess.run([...])and a fixed command plus separate arguments, not string concatenation into a shell.
Summary
input() is the standard function for console user input. It always returns a string—convert with int() or float() for numbers. Handle bad numeric input with try/except ValueError, use split() for multiple values on one line, and strip() / lower() for cleaner comparisons. In asyncio, wrap blocking input() with asyncio.to_thread() or use aioconsole. For passwords use getpass, not input(). For startup CLI flags, prefer argparse over interactive prompts.

