Python User Input
Learn how to read user input in Python with input(), convert types, validate data, handle errors, and build interactive command-line programs.
Python's built-in input() function lets your programs pause and wait for a user to type something. This chapter covers everything you need to read, validate, and convert user input — from a one-liner prompt to robust input loops that reject bad data.
What you will learn:
- How
input()works and what it always returns - Converting string input to numbers and other types
- Prompting for multiple values on one line
- Validating input with loops and
try/except - Reading passwords without echoing characters
- Common pitfalls and how to avoid them
The input() Function
input() displays an optional prompt, waits for the user to press Enter, and returns everything the user typed as a string.
name = input("What is your name? ")
print("Hello, " + name + "!")Example session:
What is your name? Alice
Hello, Alice!Two things to notice:
- The prompt string is printed to the terminal without a newline — the cursor sits right after the
?. - The return value is always a
str, even if the user types42.
If you call input() with no argument, it shows no prompt but still waits for input:
value = input() # silent promptConverting Input to Other Types
Because input() always returns a string, you must cast the value when you need a number or another type. Python's built-in conversion functions make this straightforward.
Integer input
age = int(input("Enter your age: "))
print("In ten years you will be", age + 10)Enter your age: 25
In ten years you will be 35Float input
price = float(input("Enter the price: "))
tax = price * 0.08
print(f"Tax: ${tax:.2f}")Enter the price: 19.99
Tax: $1.60Boolean-style input
Python has no bool() shortcut for "yes/no" text, so check the string directly:
answer = input("Continue? (yes/no): ").strip().lower()
if answer == "yes":
print("Continuing...")
else:
print("Stopping.")For a full reference on Python's type system, see the Python Data Types and Python Casting chapters.
Reading Multiple Values at Once
Users sometimes need to enter several values on a single line. str.split() divides the input string into a list.
# Read three space-separated integers
a, b, c = input("Enter three numbers separated by spaces: ").split()
a, b, c = int(a), int(b), int(c)
print("Sum:", a + b + c)Enter three numbers separated by spaces: 4 7 2
Sum: 13You can also use a custom separator:
first, last = input("Enter your full name (first,last): ").split(",")
print(f"Hello, {first.strip()} {last.strip()}!")Enter your full name (first,last): Alice,Smith
Hello, Alice Smith!map() is a concise way to convert all parts at once:
numbers = list(map(int, input("Enter numbers: ").split()))
print("Numbers:", numbers)
print("Total:", sum(numbers))Enter numbers: 3 1 4 1 5 9
Numbers: [3, 1, 4, 1, 5, 9]
Total: 23Handling Invalid Input with try/except
If the user types something unexpected — letters where you expected a number — the conversion raises a ValueError and crashes the program unless you catch it.
Basic error handling
try:
age = int(input("Enter your age: "))
print("Valid age:", age)
except ValueError:
print("That is not a valid number. Please enter digits only.")Enter your age: twenty
That is not a valid number. Please enter digits only.See the Python Try Except chapter for a complete guide to exception handling.
Repeating the prompt until valid input is given
A while True loop combined with break is the standard pattern for "keep asking until the user gets it right":
while True:
try:
age = int(input("Enter your age: "))
if age < 0 or age > 130:
print("Please enter a realistic age (0-130).")
else:
break # valid input received
except ValueError:
print("That is not a valid number. Please try again.")
print(f"Your age is {age}.")Example session:
Enter your age: abc
That is not a valid number. Please try again.
Enter your age: -5
Please enter a realistic age (0-130).
Enter your age: 28
Your age is 28.This pattern — loop, try/except, range check, break — covers the vast majority of real-world input validation needs.
See Python While Loops for more on loop control.
Stripping Whitespace
Users often accidentally add a leading or trailing space. Always call .strip() on text input before comparing or storing it:
username = input("Username: ").strip()
if username == "admin":
print("Welcome, administrator!")
else:
print(f"Welcome, {username}!").lower() or .upper() helps with case-insensitive comparisons:
city = input("Enter your city: ").strip().lower()
if city == "new york":
print("You are in the Big Apple!")Input Validation with Conditions
For choices or patterns, check the value directly after stripping and normalising:
color = input("Choose a color (red/green/blue): ").strip().lower()
valid_colors = {"red", "green", "blue"}
if color not in valid_colors:
print(f"'{color}' is not a valid choice. Pick red, green, or blue.")
else:
print(f"You chose {color}.")Validating with regular expressions
The re module lets you check that input matches a specific pattern:
import re
email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
email = input("Enter your email address: ").strip()
if re.match(email_pattern, email):
print("Valid email address.")
else:
print("Invalid email address. Please include '@' and a domain.")Enter your email address: [email protected]
Valid email address.Note: The regex above is simplified for demonstration. Production systems typically use a dedicated library (such as
email-validator) or server-side validation for email addresses.
Reading Passwords Securely
The standard input() function echoes characters to the terminal as the user types. For passwords and other secrets, use getpass.getpass() from the standard library — it hides the typed characters:
import getpass
password = getpass.getpass("Enter your password: ")
print("Password received (length:", len(password), "characters).")getpass.getpass() accepts the same optional prompt string as input(). The terminal suppresses the characters; the returned value is a plain string.
Formatted Output from Input
Once you have the user's data, Python's f-strings make it easy to present it clearly. See the Format Strings chapter for details.
name = input("Name: ").strip().title()
birth_year = int(input("Birth year: "))
current_year = 2025
age = current_year - birth_year
print(f"\n--- Profile ---")
print(f"Name : {name}")
print(f"Born : {birth_year}")
print(f"Age : {age}")Name: alice smith
Birth year: 1995
--- Profile ---
Name : Alice Smith
Born : 1995
Age : 30Python 2 vs Python 3
If you encounter older Python 2 code, note that the equivalent function was called raw_input(). In Python 2, input() evaluated the expression the user typed (similar to eval()), which was a security risk. In Python 3, input() always returns a plain string and raw_input() no longer exists.
# Python 2 (legacy — do not use)
# name = raw_input("Your name: ")
# Python 3 (correct)
name = input("Your name: ")Common Pitfalls
| Mistake | What goes wrong | Fix |
|---|---|---|
age = int(input(...)) without try/except | Crashes on non-numeric input | Wrap in try/except ValueError |
Forgetting .strip() | " admin" does not equal "admin" | Always strip text input |
| Comparing raw input to an int | input() == 5 is always False | Convert first: int(input(...)) == 5 |
Using input() for passwords | Characters visible on screen | Use getpass.getpass() |
Expecting bool(input(...)) to work | Any non-empty string is truthy | Parse the string: == "yes" |
Quick Reference
# String input
name = input("Name: ").strip()
# Integer input with validation
while True:
try:
n = int(input("Enter a number: "))
break
except ValueError:
print("Integers only, please.")
# Float input
price = float(input("Price: "))
# Multiple values on one line
x, y = map(int, input("Enter x y: ").split())
# Password (hidden input)
import getpass
pwd = getpass.getpass("Password: ")
# Choice validation
choice = input("(yes/no): ").strip().lower()
if choice not in ("yes", "no"):
print("Please type yes or no.")Related Topics
- Python Variables — storing and naming values
- Python Data Types — strings, integers, floats, and more
- Python Casting — converting between types
- Python Strings — methods like
.strip(),.lower(),.split() - Python Try Except — catching and handling exceptions
- Python While Loops — repeating until a condition is met
- Format Strings — building output strings with f-strings