Getting User Input
The input() function is Python's way of getting data from the user. When your program encounters input(), it pauses execution and waits for the user to type something and press Enter.
Important: The input() function always returns a string, even if the user types a number. You must convert it if you need a different type.
name = input("What is your name? ")
print(f"Hello, {name}!")
response = input()
first_name = input("First name: ")
last_name = input("Last name: ")
print(f"Full name: {first_name} {last_name}")
Converting Input
Since input() always returns a string, you need to convert it when you want to do mathematical operations or need a different data type:
age_str = input("Enter your age: ")
age = int(age_str)
birth_year = 2024 - age
print(f"You were born in {birth_year}")
price_str = input("Enter price: ")
price = float(price_str)
total = price * 1.08
print(f"Total with tax: ${total:.2f}")
Handling Multiple Inputs
You can get multiple inputs from the user in sequence:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height (feet): "))
print(f"\nName: {name}")
print(f"Age: {age}")
print(f"Height: {height} feet")
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
print(f"{num1} + {num2} = {num1 + num2}")
Input Validation
It's important to validate user input to handle errors gracefully. Users might enter invalid data:
while True:
age_input = input("Enter your age: ")
if age_input.isdigit():
age = int(age_input)
if age > 0 and age < 120:
break
else:
print("Please enter a valid age (0-120)")
else:
print("Please enter a number")
print(f"You entered: {age}")
try:
price = float(input("Enter price: $"))
print(f"Price: ${price:.2f}")
except ValueError:
print("Invalid price format!")
Practical Examples
Here are some real-world examples of using input:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operation (+, -, *, /): ")
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
else:
result = "Invalid operator"
print(f"Result: {result}")
username = input("Enter username: ")
email = input("Enter email: ")
age = int(input("Enter age: "))
print(f"\nProfile Created!")
print(f"Username: {username}")
print(f"Email: {email}")
print(f"Age: {age}")
Input Best Practices
โ
Good Practices
โข Always provide clear prompts that tell users what to enter
โข Validate input before using it
โข Convert input to the correct type immediately after receiving it
โข Handle errors with try/except blocks
โข Give users clear error messages if input is invalid
โ Common Mistakes
โข Forgetting that input() returns a string
โข Not converting numeric input before doing math
โข Not validating user input
โข Using input() in a loop without validation (can cause infinite loops)
๐ Note for This Environment
In this web-based learning environment, input() doesn't work interactively. We simulate it with pre-defined values. In a real Python environment (like running Python from the terminal), input() will pause your program and wait for keyboard input!
๐
Lesson Complete!
Great work! Continue to the next lesson.