Chapter 4: User Input 🎮
So far, your programs have been one-way conversations — you write the code, and Python displays the results. But what if you want your program to ask questions and respond to answers? That’s where user input comes in!
User input transforms your programs from static scripts into interactive experiences. Think about it: every game you play, every app you use, they all respond to what you do. Now you’ll learn how to make your programs do the same.
Getting User Input: Making Programs Interactive 💬
Python has a built-in function called input() that pauses your program and waits for the user to type something. When the user presses Enter, Python captures what they typed and gives it to your program.
The Basic Syntax
Here’s the simplest way to use input():
name = input("What is your name? ")
print("Hello,", name)
When you run this program:
- Python displays the question: “What is your name? ”
- The program pauses and waits
- You type your answer (let’s say “Jordan”) and press Enter
- Python stores “Jordan” in the
namevariable - The program continues and prints: “Hello, Jordan”
Important details:
- The text inside
input()is called a prompt — it tells the user what to enter - Notice the space after the question mark:
"What is your name? "— this makes the cursor appear after the space, making it look nicer - Whatever the user types is captured as a string (text), even if they type numbers
Making It Personal
Input makes your programs feel alive and responsive. Instead of showing the same thing every time, they adapt to each user:
favorite_color = input("What's your favorite color? ")
print(f"Wow, {favorite_color} is a great color!")
hobby = input("What do you like to do for fun? ")
print(f"{hobby} sounds really interesting!")
Each time someone runs this program, they get a unique, personalized experience.
Multiple Inputs
You can ask for as much information as you need. Just make sure to store each answer in a different variable:
# A simple character creator
print("=== Character Creator ===")
print()
character_name = input("Enter your character's name: ")
character_race = input("Enter your character's race (Elf, Dwarf, Human): ")
character_weapon = input("Choose your weapon: ")
print()
print("=== Your Character ===")
print(f"Name: {character_name}")
print(f"Race: {character_race}")
print(f"Weapon: {character_weapon}")
print()
print("Your adventure begins!")
This creates an interactive character creation experience. The user feels engaged because the program responds to their choices.
Input Without a Prompt
You don’t have to provide a prompt, but it’s almost always better to include one so users know what to do:
# No prompt - confusing for the user
answer = input()
# With prompt - clear and helpful
answer = input("Enter your answer: ")
Best practice: Always include a clear, specific prompt that tells users exactly what information you’re asking for.
Converting Data Types: Understanding Input 🔄
Here’s something crucial to understand: input() always returns a string, even if the user types numbers. This can cause unexpected problems when you want to do math.
The Problem
Let’s say you want to ask for someone’s age and add 1 to it:
age = input("How old are you? ")
next_year_age = age + 1 # ERROR! Can't add a number to a string
This causes an error because age is a string (like "14"), not a number. Python doesn’t know if you want to do math or text concatenation.
Even more confusing:
age = input("How old are you? ") # User types: 14
print(age + age) # Shows: 1414 (not 28!)
It treats the numbers as text and concatenates them instead of adding them mathematically.
The Solution: Type Conversion
Python provides functions to convert data from one type to another. The most common ones are:
int()— converts to an integer (whole number)float()— converts to a float (decimal number)str()— converts to a string (text)
Converting to Integers
When you need whole numbers (like age, score, quantity), use int():
# Method 1: Convert after getting input
age_text = input("How old are you? ")
age = int(age_text)
next_year = age + 1
print(f"Next year you'll be {next_year}!")
# Method 2: Convert immediately (more common)
age = int(input("How old are you? "))
next_year = age + 1
print(f"Next year you'll be {next_year}!")
Method 2 is cleaner and more common. Here’s what happens:
input("How old are you? ")gets the user’s input as a stringint()converts that string to an integer- The integer is stored in the
agevariable
Now you can use age in mathematical calculations:
current_age = int(input("Enter your age: "))
# Math works perfectly!
age_in_5_years = current_age + 5
age_in_months = current_age * 12
print(f"In 5 years, you'll be {age_in_5_years}")
print(f"You've lived approximately {age_in_months} months")
Converting to Floats
When you need decimal numbers (like prices, measurements, temperatures), use float():
height = float(input("Enter your height in meters: "))
print(f"Your height is {height}m")
price = float(input("Enter the item price: $"))
quantity = int(input("How many items? "))
total = price * quantity
print(f"Total cost: ${total:.2f}")
Notice how we used int() for quantity (you can’t buy 2.5 items in most cases) but float() for price (because prices have cents).
Type Conversion in Action
Here’s a practical example that uses multiple conversions:
print("=== Simple Calculator ===")
# Get two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform calculations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
# Display results
print()
print("Results:")
print(f"{num1} + {num2} = {addition}")
print(f"{num1} - {num2} = {subtraction}")
print(f"{num1} × {num2} = {multiplication}")
print(f"{num1} ÷ {num2} = {division:.2f}")
We used float() instead of int() because users might enter decimal numbers. This makes our calculator more flexible.
What If the User Enters Invalid Data?
If you try to convert text that isn’t a number, Python will crash with an error:
age = int(input("Enter your age: ")) # User types: "hello"
# ERROR: ValueError: invalid literal for int() with base 10: 'hello'
For now, just make sure your prompts are clear so users know to enter numbers. In a future chapter, you’ll learn how to handle errors gracefully using try/except blocks.
Quick tips to avoid errors:
- Make your prompts very specific: “Enter your age as a number: ”
- If you’re building something for others to use, test it with different inputs
- You’ll learn error handling later in the series
Converting Back to Strings
Sometimes you might need to convert numbers back to strings, especially for concatenation:
score = 100
level = 5
# This would cause an error:
# message = "Level " + level # Can't concatenate string and int
# Solution: convert to string
message = "Level " + str(level)
print(message) # Shows: Level 5
# Or better yet, use f-strings (they handle conversion automatically!)
message = f"Level {level}"
print(message) # Shows: Level 5
This is why f-strings are so convenient — they automatically convert numbers to strings for you!
Combining Input with Everything You’ve Learned 🌟
Now that you can get input and convert types, your programs can be truly interactive. Let’s see how input combines with strings, variables, and math:
Example 1: Personalized Greeting
name = input("What's your name? ")
age = int(input("How old are you? "))
print()
print(f"Hello, {name.title()}!")
print(f"You've been alive for about {age * 365} days.")
print(f"That's roughly {age * 365 * 24} hours!")
This combines:
- User input
- String methods (
.title()) - Type conversion (
int()) - Math operations
- F-strings for formatting
Example 2: Price Calculator
print("=== Shopping Cart ===")
item = input("What are you buying? ")
price = float(input("Price per item: $"))
quantity = int(input("How many? "))
subtotal = price * quantity
tax_rate = 0.08 # 8% tax
tax = subtotal * tax_rate
total = subtotal + tax
print()
print(f"Item: {item.title()}")
print(f"Price: ${price:.2f} each")
print(f"Quantity: {quantity}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"=" * 30)
print(f"Total: ${total:.2f}")
This example shows how input makes a program practical and useful. Instead of hard-coding values, users can calculate any purchase!
Example 3: Mad Libs Game
Remember Mad Libs? Let’s create one:
print("=== Mad Libs: Space Adventure ===")
print("Fill in the words to create a funny story!")
print()
adjective1 = input("Enter an adjective: ")
noun1 = input("Enter a noun: ")
verb = input("Enter a verb (past tense): ")
adjective2 = input("Enter another adjective: ")
noun2 = input("Enter another noun: ")
number = input("Enter a number: ")
print()
print("=== Your Story ===")
print()
story = f"""
Once upon a time, in a {adjective1} galaxy far away,
a brave astronaut named Captain {noun1} {verb}
through space in a {adjective2} spaceship.
They were searching for the legendary {noun2},
which was said to be {number} light-years away.
"""
print(story)
print()
print("The End!")
This demonstrates how fun and creative programming can be. The user provides random words, and your program weaves them into a story!
Quick Recap 🎯
You’ve just unlocked interactive programming! Here’s what you learned:
✅ input() gets text from users and pauses until they press Enter
✅ Always include a clear prompt to tell users what to enter
✅ input() always returns a string, even for numbers
✅ int() converts strings to whole numbers
✅ float() converts strings to decimal numbers
✅ Combining input with other concepts creates powerful, interactive programs
Your programs can now have conversations with users!
🚀 Hands-On Exercise: Build a Fitness Tracker
Create an interactive program that calculates fitness statistics based on user input.
Your Mission:
-
Ask the user for:
- Their name
- Their weight in kilograms (use
float()) - Their height in meters (use
float()) - How many minutes they exercised today (use
int())
-
Calculate:
- BMI (Body Mass Index) = weight ÷ (height × height)
- Calories burned (estimate: 5 calories per minute of exercise)
-
Display a personalized fitness report with:
- A greeting using their name
- Their BMI rounded to 1 decimal place
- Total calories burned
- Encouraging message
Example Solution:
print("=== Personal Fitness Tracker ===")
print()
# Get user information
name = input("Enter your name: ")
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))
exercise_minutes = int(input("How many minutes did you exercise today? "))
# Calculations
bmi = weight / (height * height)
calories_burned = exercise_minutes * 5
# Display report
print()
print("=" * 40)
print(f"FITNESS REPORT FOR {name.upper()}")
print("=" * 40)
print()
print(f"Weight: {weight} kg")
print(f"Height: {height} m")
print(f"BMI: {bmi:.1f}")
print()
print(f"Exercise Time: {exercise_minutes} minutes")
print(f"Estimated Calories Burned: {calories_burned}")
print()
# Encouraging message based on exercise time
if exercise_minutes > 30:
print("🌟 Great job! You're crushing your fitness goals!")
elif exercise_minutes > 0:
print("💪 Good work! Every minute counts!")
else:
print("🏃 Even a short walk can make a difference!")
print()
print("=" * 40)
Challenge Yourself:
- Ask for multiple days of exercise and calculate the weekly total
- Convert height from feet/inches to meters within the program
- Calculate how many days it would take to burn 1000 calories at their current rate
- Add more health metrics (age, activity level, etc.)
- Make the report even more visually appealing with borders and formatting
Remember: Test your program with different inputs. What happens if someone is very tall or very short? Does your program handle decimal numbers properly?
What’s Next? 🤔
In the next chapter, you’ll learn about booleans and decision-making. You’ll discover how to make your programs smart enough to respond differently based on user input — like giving different messages depending on someone’s age or score!
Your programs are getting more powerful with every chapter! Keep experimenting!