The input() function lets a Python program pause, show a prompt, and wait for the user to type a response. It is the foundation of command-line forms, calculators, menus, quizzes, and many beginner projects.
The most important rule is simple: the Python input function always returns text. Even when the user types 25, Python receives the string "25" until you convert it.
Your First input() Example
name = input("What is your name? ")
print(f"Hello, {name}!")The prompt is printed without an automatic newline, the program waits, and the entered text is assigned to name. The official behavior is described in the Python input() documentation.
input() Always Returns a String
age = input("Age: ")
print(type(age))The output is <class 'str'>. Convert the string before numerical calculations:
age = int(input("Age: "))
print(f"Next year you will be {age + 1}.")Use float() when decimal values are allowed:
height = float(input("Height in meters: "))
print(f"Height: {height:.2f} m")The guides to Python integers and built-in functions explain conversion in more detail.
Remove Unwanted Spaces
Users often add spaces before or after text. strip() removes them.
name = input("Name: ").strip()
email = input("Email: ").strip().lower()
print(name)
print(email)Normalization makes comparisons more reliable, but do not silently change data when capitalization is meaningful.
Validate an Integer with try and except
Direct conversion raises ValueError when the text is not a valid integer.
try:
age = int(input("Age: "))
print(f"Registered age: {age}")
except ValueError:
print("Please enter a whole number.")This handles one attempt. For a real form, repeat until the value is valid.
while True:
try:
age = int(input("Age: "))
except ValueError:
print("Enter a whole number.")
continue
if age < 0 or age > 130:
print("Enter a realistic age.")
continue
break
print(f"Valid age: {age}")The try and except guide explains specific exceptions and validation patterns. The loops guide covers while, break, and continue.
Create Reusable Input Functions
Repeated validation belongs in a function.
def read_integer(prompt: str, minimum=None, maximum=None) -> int:
while True:
try:
value = int(input(prompt))
except ValueError:
print("Enter a valid whole number.")
continue
if minimum is not None and value < minimum:
print(f"The minimum value is {minimum}.")
continue
if maximum is not None and value > maximum:
print(f"The maximum value is {maximum}.")
continue
return value
quantity = read_integer("Quantity: ", minimum=1, maximum=100)
print(f"Quantity accepted: {quantity}")This function separates user-interface concerns from business logic. Learn more in the Python functions guide.
Read Decimal Values Safely
def read_float(prompt: str, minimum=None) -> float:
while True:
text = input(prompt).strip()
try:
value = float(text)
except ValueError:
print("Enter a valid number, such as 12.50.")
continue
if minimum is not None and value < minimum:
print(f"The value must be at least {minimum}.")
continue
return value
price = read_float("Price: $", minimum=0)
print(f"Price: ${price:.2f}")Money applications often require Decimal rather than binary floating-point arithmetic. The conversion and rounding policy should match the application’s requirements.
Ask Yes-or-No Questions
def ask_yes_no(prompt: str) -> bool:
while True:
answer = input(f"{prompt} [y/n]: ").strip().lower()
if answer in {"y", "yes"}:
return True
if answer in {"n", "no"}:
return False
print("Please answer y or n.")
if ask_yes_no("Save changes?"):
print("Changes saved.")
else:
print("Operation cancelled.")A set makes the accepted values explicit. See the Python sets tutorial for membership examples.
Build a Terminal Menu
def show_menu():
print("\n1. Add task")
print("2. List tasks")
print("3. Exit")
while True:
show_menu()
option = input("Choose an option: ").strip()
if option == "1":
print("Add-task selected")
elif option == "2":
print("List-tasks selected")
elif option == "3":
print("Goodbye!")
break
else:
print("Invalid option.")Keeping the option as text avoids unnecessary conversion and makes comparisons direct. As the menu grows, route actions through functions or a dictionary.
Read Multiple Values on One Line
split() divides text at whitespace.
first_name, last_name = input("First and last name: ").split(maxsplit=1)
print(first_name)
print(last_name)For several numbers:
numbers = [int(value) for value in input("Enter numbers: ").split()]
print(f"Total: {sum(numbers)}")This compact version raises ValueError if any item is invalid. A safer version validates each token:
def read_integer_list(prompt: str) -> list[int]:
while True:
parts = input(prompt).split()
try:
return [int(part) for part in parts]
except ValueError:
print("Use whole numbers separated by spaces.")
values = read_integer_list("Numbers: ")
print(values)Handle Optional Input
Sometimes pressing Enter should select a default.
city = input("City [London]: ").strip() or "London"
print(f"Selected city: {city}")For optional numeric input, check the text before conversion:
text = input("Discount percentage [none]: ").strip()
discount = 0.0 if text == "" else float(text)
print(discount)Do Not Use input() for Visible Passwords
input() displays every typed character. Use the standard-library getpass module for secrets entered in a terminal.
from getpass import getpass
username = input("Username: ").strip()
password = getpass("Password: ")
print(f"Credentials received for {username}")Do not print, log, or store plain-text passwords. A real authentication system should use established password hashing and secure storage.
Cancel Input Gracefully
Users may press Ctrl+C or send an end-of-file signal. Command-line programs can handle these cases at the outermost level.
def main():
name = input("Name: ").strip()
print(f"Hello, {name}!")
try:
main()
except (KeyboardInterrupt, EOFError):
print("\nInput cancelled.")Do not wrap every line in a broad handler. Keep expected validation near the input and application-level cancellation near the program entry point.
input() Is Blocking
While input() waits, the current thread does not continue. This is fine for small terminal applications. It is usually inappropriate inside graphical interfaces, web servers, asynchronous tasks, or background services because it can freeze or block the application.
Web applications receive data through HTTP forms or APIs. Desktop interfaces use events and widgets. Asynchronous programs use compatible input mechanisms. Choose the input method that matches the environment.
Keep Input Separate from Logic
A function that calls input() directly is harder to test. Prefer pure functions for calculations.
def calculate_total(price: float, quantity: int) -> float:
if price < 0:
raise ValueError("Price cannot be negative")
if quantity < 1:
raise ValueError("Quantity must be positive")
return price * quantity
price = read_float("Price: $", minimum=0)
quantity = read_integer("Quantity: ", minimum=1)
print(f"Total: ${calculate_total(price, quantity):.2f}")The calculation can now be tested without simulating keyboard input. The Pytest guide shows how to test functions and exceptions.
Practical Project: Grade Calculator
def read_grade(label: str) -> float:
while True:
try:
grade = float(input(f"{label} (0-100): "))
except ValueError:
print("Enter a numeric grade.")
continue
if 0 <= grade <= 100:
return grade
print("The grade must be between 0 and 100.")
grades = [
read_grade("Assignment"),
read_grade("Project"),
read_grade("Exam"),
]
average = sum(grades) / len(grades)
status = "passed" if average >= 60 else "failed"
print(f"Average: {average:.1f}")
print(f"Result: {status}")This project combines input, conversion, validation, functions, lists, calculations, conditions, and formatted output.
Common Mistakes
Doing Arithmetic on Text
first = input("First number: ")
second = input("Second number: ")
print(first + second) # joins stringsTyping 2 and 3 prints 23. Convert first:
first = int(input("First number: "))
second = int(input("Second number: "))
print(first + second)Calling int() Before Handling Empty Input
# int("") raises ValueError
text = input("Quantity [1]: ").strip()
quantity = 1 if text == "" else int(text)Using eval() on User Input
# Dangerous: never evaluate arbitrary user text
# result = eval(input("Expression: "))eval() can execute code. Parse only the specific formats your program accepts.
Trusting Input Without Business Validation
A valid integer can still be unacceptable. An age of -10 converts successfully but should fail domain validation. Separate syntactic conversion from business rules.
Frequently Asked Questions
Why does input() return a string?
Keyboard input arrives as text. Python cannot know whether the text represents an age, price, date, name, or code, so the program must convert it deliberately.
How do I keep asking until the input is valid?
Use a while loop, catch the expected conversion exception, validate the allowed range, and return or break only after success.
How do I accept a default value?
Strip the text and check whether it is empty before conversion, or use value = input(...).strip() or default for text defaults.
Can input() read several values?
Yes. Read one line, split it into parts, then convert and validate each part.
Is input() suitable for web applications?
No. Web applications receive input through requests, forms, JSON bodies, query parameters, and uploaded files.
Conclusion
input() makes terminal programs interactive, but useful input handling requires normalization, conversion, validation, clear error messages, and reusable functions. Treat all external input as untrusted, keep secrets hidden, separate interface code from business logic, and test calculations independently.






