Python 3 — Reading User Inputs
Every interactive program needs to accept input from users. Python provides the built-in input() function to pause execution, display a prompt, and wait for the user to type something. This lesson covers reading inputs, converting types, validating data, and building real interactive programs.
The input() function displays a prompt to the user, waits for them to type something, and returns their response as a string:
# Basic input - always returns a string
name = input("What is your name? ")
print(f"Hello, {name}! Welcome to Python.")
# Empty prompt (no message)
value = input()
print(f"You typed: {value}")
Critical: input() always returns a string, even if the user types a number. You must convert it to the correct type before doing math:
# String to Integer
age = int(input("Enter your age: "))
print(f"In 10 years, you will be {age + 10}")
# String to Float
price = float(input("Enter price: "))
tax = price * 0.18
print(f"Price with 18% tax: {price + tax:.2f}")
# Multiple inputs on one line using split()
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"Sum = {x + y}, Product = {x * y}")
Python's split() and map() functions make it easy to read multiple values in one line:
# Read a list of numbers
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
print(f"Average: {sum(numbers) / len(numbers):.2f}")
print(f"Max: {max(numbers)}, Min: {min(numbers)}")
# Read 3 values at once
a, b, c = map(float, input("Enter 3 values: ").split())
print(f"Average of {a}, {b}, {c} = {(a+b+c)/3:.2f}")
Users often type unexpected things. Use try-except to safely handle invalid inputs:
# Safe integer input with error handling
def get_integer(prompt):
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("❌ Invalid! Please enter a whole number.")
# age = get_integer("Enter your age: ")
# print(f"Age: {age}")
# Validate range
def get_score():
while True:
try:
score = int(input("Enter score (0-100): "))
if 0 <= score <= 100:
return score
else:
print("❌ Score must be between 0 and 100!")
except ValueError:
print("❌ Please enter a number!")
# score = get_score()
# print(f"Valid score: {score}")
Let's build a complete interactive calculator using everything we've learned:
print("=== Simple Calculator ===")
try:
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("❌ Cannot divide by zero!")
else:
result = num1 / num2
else:
print("❌ Unknown operator!")
result = None
if result is not None:
print(f"Result: {num1} {operator} {num2} = {result}")
except ValueError:
print("❌ Please enter valid numbers!")
Combine input() with loops to keep asking until the user provides valid data or decides to quit:
# Collect items until user types 'done'
shopping_list = []
print("Enter items (type 'done' to finish):")
while True:
item = input("Add item: ").strip()
if item.lower() == "done":
break
if item:
shopping_list.append(item)
print(f"✅ Added: {item}")
else:
print("❌ Item cannot be empty!")
print(f"
Your shopping list ({len(shopping_list)} items):")
for i, item in enumerate(shopping_list, 1):
print(f" {i}. {item}")
For sensitive inputs like passwords, use getpass.getpass() which hides the typed characters:
import getpass
# getpass hides input in terminal (appears blank while typing)
# In Our Compiler, it works like regular input()
username = input("Username: ")
password = getpass.getpass("Password: ") # Hidden input
correct_user = "admin"
correct_pass = "python123"
if username == correct_user and password == correct_pass:
print("✅ Login successful! Welcome, Admin.")
else:
print("❌ Invalid credentials. Access denied.")
- Forgetting to convert:
int(input(...))— withoutint(), math operations will fail or concatenate strings - Not handling
ValueErrorwhen user types text instead of a number - Using
input()in a loop without a way to exit — always have abreakcondition - Forgetting
.strip()to remove leading/trailing whitespace from input
Build a Number Guessing Game:
- Set a secret number (e.g., 42)
- Ask the user to guess in a loop
- After each guess, tell them if it's "Too high", "Too low", or "Correct!"
- Count how many attempts it takes
- Print "Congratulations! You got it in X attempts!"
- Handle non-numeric inputs gracefully with try-except