Getting User Input with input()
What You'll Learn
- How the
input()function works - Why
input()always returns a string - How to convert user input to numbers
- Building interactive programs
- Common input patterns and mistakes
1. The input() Function
name = input("What is your name? ") print("Hello,", name + "!")
Hello, Alice!
When Python encounters input(), it:
- Displays the prompt text (if provided)
- Pauses and waits for the user to type
- When the user presses Enter, returns what they typed as a string
- Stores the result in the variable
"Enter name: " not "Enter name:") so the user's typing does not bump against the prompt.
2. input() Always Returns a String
This is the most important thing to remember about input(): it always returns a string, even if the user types a number.
age = input("Enter your age: ") print(type(age)) print(age)
<class 'str'>
25
Even though the user typed 25, Python stores it as the string "25", not the number 25. This means you cannot do math with it directly:
age = input("Enter your age: ") # This would cause an error! # next_year = age + 1 # TypeError: can't add str and int
input() results to numbers before doing math. This is one of the most common errors beginners encounter!
3. Converting Input to Numbers
To do math with user input, wrap the input() call with int() or float():
# For whole numbers, use int() age = int(input("Enter your age: ")) next_year = age + 1 print("Next year you will be", next_year) # For decimal numbers, use float() price = float(input("Enter the price: $")) tax = price * 0.09 print("Tax:", tax)
Next year you will be 26
Enter the price: $19.99
Tax: 1.7991
Two Approaches to Converting
# Approach 1: Convert immediately (most common) age = int(input("Age: ")) # Approach 2: Get input first, then convert age_text = input("Age: ") age = int(age_text)
Both approaches work. Approach 1 is more concise and is the standard pattern.
4. Building Interactive Programs
Simple Calculator
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print("Sum:", num1 + num2) print("Difference:", num1 - num2) print("Product:", num1 * num2) print("Quotient:", num1 / num2)
Enter second number: 3
Sum: 13.0
Difference: 7.0
Product: 30.0
Quotient: 3.3333333333333335
Personalized Greeting
name = input("What is your name? ") color = input("What is your favorite color? ") food = input("What is your favorite food? ") print() print("Nice to meet you,", name + "!") print("I hear you love", color, "and", food + ".")
What is your favorite color? blue
What is your favorite food? pizza
Nice to meet you, Alex!
I hear you love blue and pizza.
5. Common Input Patterns
Getting Multiple Inputs for a Calculation
# Tip calculator bill = float(input("Enter the bill amount: $")) tip_percent = float(input("Tip percentage (e.g., 15, 20): ")) tip_amount = bill * (tip_percent / 100) total = bill + tip_amount print("Tip: $" + str(round(tip_amount, 2))) print("Total: $" + str(round(total, 2)))
Tip percentage (e.g., 15, 20): 20
Tip: $9.1
Total: $54.6
6. What Happens When Input Goes Wrong
If the user types something that cannot be converted, Python will raise a ValueError:
# If the user types "abc" when asked for a number: age = int(input("Enter your age: ")) # User types "abc" # ValueError: invalid literal for int() with base 10: 'abc'
For now, just be aware this can happen. You will learn how to handle errors gracefully in a later module when we cover try/except.
Check Your Understanding
Question 1: What type does input() always return?
Answer: String (str). Always. Even if the user types a number.
Question 2: How do you get a decimal number from the user?
Answer: number = float(input("Enter a number: ")) -- wrap input() with float().
Try It Yourself!
- Write a program that asks for the user's name and age, then tells them what year they were born (approximately).
- Create a program that asks for the length and width of a room, then calculates and prints the area.
- Build a "Mad Libs" program that asks for a noun, adjective, and verb, then prints a silly sentence using them.
Key Takeaways
input(prompt)displays a prompt, waits for user typing, and returns a string.input()always returns a string -- you must convert for math.- Use
int(input(...))for whole numbers andfloat(input(...))for decimals. - Always include a space at the end of your prompt text for readability.
- Clear prompts tell users exactly what to enter.