Python User Input ⌨️
Interacting with Users
Python allows for user input via the input() function. The program pauses until the user types something and presses Enter.
🍽️ Analogy: The Waiter
Think of input() as a Waiter.
- The waiter comes to your table (Program pauses).
- Asks "What would you like?" (Prompt message).
- Waits for you to speak (User types).
- Writes it down on a notepad (Returns a string).
✨ Basic Input
The input() function always returns a string.
python
name = input("Enter your name: ")
print("Hello, " + name)🔢 Numeric Input
Since input returns a string, you must convert (cast) it if you need a number.
python
age_str = input("Enter your age: ")
age = int(age_str) # Convert to integer
print(f"Next year you will be {age + 1}")🎯 Real-World Application: CLI Tools
Command Line Interface (CLI) tools rely heavily on user input for configuration.
python
print("Welcome to the Setup Wizard!")
username = input("Choose a username: ").strip()
password = input("Choose a password: ").strip()
print(f"Account created for {username}!")⚠️ Input Validation
Always validate user input to prevent errors. If the user types "abc" instead of a number, int() will crash the program.
python
while True:
try:
age = int(input("Enter age: "))
break
except ValueError:
print("Please enter a valid number!")