Python Basics — input() Function
input() Function
The input() function reads text from the user via the keyboard. It always returns a string, even if the user types a number.
Basic Usage
name = input("What is your name? ")
print(f"Hello, {name}!")
Interaction:
What is your name? Alice
Hello, Alice!
input() Always Returns a String
age = input("Enter your age: ")
print(type(age)) # <class 'str'> — always a string!
print(age) # "25" (a string, not a number)
This means you cannot do math with input() directly:
# ❌ This won't work as expected
num = input("Enter a number: ") # User types: 5
# print(num + 10) # TypeError: can only concatenate str to str
Type Casting User Input
Convert the input string to the type you need:
# Integer input
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
# Float input
price = float(input("Enter the price: "))
tax = price * 0.08
print(f"Tax: ${tax:.2f}")
# Boolean-like input
answer = input("Continue? (yes/no): ")
should_continue = answer.lower() == "yes"
print(should_continue) # True or False
Handling Invalid Input
Users sometimes type unexpected things. Use try/except to handle errors:
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
except ValueError:
print("That's not a valid number!")
Input Validation Loop
Keep asking until the user enters valid input:
while True:
user_input = input("Enter a number (1-100): ")
try:
number = int(user_input)
if 1 <= number <= 100:
break
else:
print("Please enter a number between 1 and 100.")
except ValueError:
print("Invalid input. Please enter a number.")
print(f"You entered: {number}")
Multi-Line Input
Read multiple values on separate lines:
print("Enter three numbers (one per line):")
a = int(input())
b = int(input())
c = int(input())
print(f"Sum: {a + b + c}")
Reading Multiple Values on One Line
# User types: 10 20 30
values = input("Enter three numbers separated by spaces: ").split()
a, b, c = int(values[0]), int(values[1]), int(values[2])
print(f"Sum: {a + b + c}")
# More concise with map()
x, y, z = map(int, input("Enter three numbers: ").split())
print(f"Sum: {x + y + z}")
Command-Line Arguments (sys.argv)
For scripts, you can also accept input via command-line arguments:
import sys
# Run: python script.py Alice 25
if len(sys.argv) >= 3:
name = sys.argv[1]
age = sys.argv[2]
print(f"Name: {name}, Age: {age}")
else:
print("Usage: python script.py <name> <age>")
python script.py Alice 25
# Name: Alice, Age: 25
Practical Example: Simple Calculator
print("=== Simple Calculator ===")
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:
result = num1 / num2
else:
print("Error: Division by zero!")
result = None
else:
print(f"Unknown operator: {operator}")
result = None
if result is not None:
print(f"{num1} {operator} {num2} = {result}")
Common Mistakes
| Mistake | Example | Fix |
|---|---|---|
| Forgetting to convert | int(input()) + 10 not input() + 10 |
Always cast for math |
| No error handling | int(input(...)) crashes on “abc” |
Wrap in try/except |
| Trailing whitespace | User adds spaces | Use .strip(): input().strip() |
Summary
input()always returns a string — cast withint(),float()as needed- Use
try/exceptto handle invalid input gracefully - Use a while loop for input validation
- Use
.split()andmap()to read multiple values on one line - Use
sys.argvfor command-line arguments - Always
.strip()user input to remove accidental whitespace
Next up: String Formatting →