The input() Function β Basics
The input() function pauses your program, displays a prompt, waits for the user to type something and press Enter, then returns what they typed as a string.
# Basic input
name = input("What is your name? ")
print(f"Hello, {name}!")
Always Returns a String β Type Conversion Required
This is the most common mistake: input() ALWAYS returns a string, even if the user types a number. You must convert it to the right type.
# β Bug: comparing string to integer
age = input("Enter your age: ") # Returns "25" (string)
if age > 18: # Error! Can't compare str > int
print("Adult")
# β
Correct: convert to int first
age = int(input("Enter your age: ")) # Now it's an integer
if age > 18:
print("Adult")
Converting Input to Different Types
Use int(), float(), or other conversion functions wrapped around input() to get the type you need.
name = input("Name: ") # str - no conversion needed
age = int(input("Age: ")) # int
price = float(input("Price: $")) # float
active = input("Active? (y/n): ") == "y" # bool
print(type(name), type(age), type(price), type(active))
Input Validation β Handling Bad Input
Users type unexpected things. Always validate input when your program depends on a specific format.
# Keep asking until valid number given
while True:
try:
age = int(input("Enter age (0-120): "))
if 0 <= age <= 120:
break
print("Age must be between 0 and 120.")
except ValueError:
print("Please enter a valid number.")
print(f"Your age is: {age}")
Getting Multiple Inputs
You can get multiple values in one line using split(), or ask separately.
# Option 1: separate inputs
first = input("First name: ")
last = input("Last name: ")
# Option 2: one line, split by space
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"Sum: {x + y}")