Skip to main content

Taking User Input

Python makes it very easy to interact with the user through the input() function. We can pass a string directly to input() to show a message to the user before they type.

Basic Input

The input() function returns a string by default, even if the user types a number.

name = input("Enter our name: ")
print(f"Hello, {name}!")
Enter our name: Alice
Hello, Alice!

Handling Numeric Input

Since input() always returns text, manual typecasting is necessary if we need to perform arithmetic with the result.

# Anti-pattern: This will crash if we try to add 10 to a string
# age = input("Enter our age: ")
# print(age + 10)

# Pythonic: Cast the input immediately
age = int(input("Enter our age: "))
print(f"Next year we will be {age + 1}!")
Enter our age: 25
Next year we will be 26!
Input Validation

If a user types something that isn't a valid number (like "apple") when we expect an integer, Python will throw a ValueError. Always ensure the input matches the expected type before casting.