Chapter 1: The Basics / Lesson 8

User Input

5 min ยท The Basics

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.

input.py
# Basic input usage name = input("What is your name? ") # Program waits here until user types and presses Enter print(f"Hello, {name}!") # Input with empty prompt (just waits) response = input() # No prompt shown, just waits # Multiple inputs 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:

input_conversion.py
# Get age as string, convert to integer age_str = input("Enter your age: ") age = int(age_str) # Convert string to int birth_year = 2024 - age print(f"You were born in {birth_year}") # Get price as string, convert to float price_str = input("Enter price: ") price = float(price_str) # Convert string to float total = price * 1.08 # Add 8% tax print(f"Total with tax: ${total:.2f}")

Handling Multiple Inputs

You can get multiple inputs from the user in sequence:

multiple_inputs.py
# Collecting multiple values 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") # Getting input and immediately converting 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:

validation.py
# Safe input with validation while True: age_input = input("Enter your age: ") if age_input.isdigit(): # Check if all characters are digits 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}") # Using try/except for safer conversion 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:

practical.py
# Simple calculator 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}") # User profile 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.

main.py
๐Ÿ“ค Output
Click "Run" to execute...