๐ฌ Lesson 4: Making Programs Interactive with Input
So far, our programs have been like someone giving a speech โ they talk, but don't listen. Now we'll make them interactive, like having a conversation!
๐ฏ Learning Objectives
By the end of this lesson, you will be able to:
- Use
input()to get data from users - Understand that
input()always returns a string - Convert input to numbers with
int()andfloat() - Validate user input and handle edge cases
- Build interactive programs that respond to user data
Estimated Time: 45โ60 minutes
Project: Build a Mad Libs game and an interactive calculator using input()
In This Lesson
๐ฃ๏ธ From Monologue to Dialogue
So far, our programs have been like someone giving a speech โ they talk, but don't listen. Now we'll make them interactive, like having a conversation!
โจ The Magic Word: input()
The input() function is like asking someone a question and waiting for their answer:
# Basic input
name = input("What's your name? ")
print(f"Nice to meet you, {name}!")
# The program will:
# 1. Display "What's your name? "
# 2. Wait for you to type something
# 3. Store what you typed in the variable 'name'
# 4. Continue with the rest of the program
Your First Interactive Program
Let's create a simple greeting program:
# greeting.py
print("Welcome to the Friendly Greeting Program!")
print("=" * 40) # This creates a line of 40 equal signs
user_name = input("What's your name? ")
user_mood = input("How are you feeling today? ")
print(f"\nHello, {user_name}!")
print(f"It's great that you're feeling {user_mood}!")
print("Have a wonderful day!")
input() function displays a prompt, waits for the user to type, and stores the result.โ ๏ธ Important: Input Always Returns Text!
Here's a crucial point: input() ALWAYS gives you text (a string), even if the user types numbers!
# This might surprise you:
age = input("How old are you? ")
# If user types: 25
# age contains: "25" (text, not a number!)
# This will cause an error:
# next_year_age = age + 1 # Can't add 1 to text!
# The solution: Convert to a number
age = input("How old are you? ")
age = int(age) # Convert text to integer
next_year_age = age + 1
print(f"Next year you'll be {next_year_age}!")
โ ๏ธ Watch Out
If you try to do math with an unconverted input, Python will throw a TypeError. Always convert your inputs to the right type before doing math!
๐ Converting Input Types
Python provides functions to convert between types:
# Converting input types in action
# Integer โ for whole numbers
age = int(input("Enter your age: "))
# Float โ for decimal numbers
height = float(input("Enter your height in feet: "))
# Shortcut โ combine input and conversion
price = float(input("Enter the price: $"))
# str() โ convert number back to text (less common with input)
score = 95
message = "Your score is " + str(score)
๐งฎ Building a Simple Calculator
Let's put it all together with an interactive calculator:
# calculator.py
print("Welcome to Python Calculator!")
print("-" * 30)
# Get the first number
num1 = input("Enter the first number: ")
num1 = float(num1) # Convert to decimal number
# Get the second number
num2 = input("Enter the second number: ")
num2 = float(num2) # Convert to decimal number
# Perform calculations
sum_result = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
# Display results
print(f"\nResults:")
print(f"{num1} + {num2} = {sum_result}")
print(f"{num1} - {num2} = {difference}")
print(f"{num1} ร {num2} = {product}")
print(f"{num1} รท {num2} = {quotient}")
Sample Output (user enters 10 and 3):
Welcome to Python Calculator!
------------------------------
Enter the first number: 10
Enter the second number: 3
Results:
10.0 + 3.0 = 13.0
10.0 - 3.0 = 7.0
10.0 ร 3.0 = 30.0
10.0 รท 3.0 = 3.3333333333333335
๐ค Making Input More User-Friendly
Good programs guide users and handle mistakes gracefully:
# Temperature Converter
print("Temperature Converter")
print("I'll convert Celsius to Fahrenheit for you!")
print()
celsius = input("Enter temperature in Celsius: ")
celsius = float(celsius)
fahrenheit = (celsius * 9/5) + 32
print(f"\n{celsius}ยฐC is equal to {fahrenheit}ยฐF")
# Adding context
if fahrenheit < 32:
print("That's below freezing! Bundle up! ๐ฅถ")
elif fahrenheit > 85:
print("That's pretty hot! Stay hydrated! โ๏ธ")
else:
print("That's comfortable weather! ๐")
๐ Creating Menu-Driven Programs
Menus make programs easier to navigate:
# Menu-driven calculator
def show_menu():
print("\n" + "="*30)
print(" CALCULATOR MENU")
print("="*30)
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
print("-"*30)
while True:
show_menu()
choice = input("Select operation (1-5): ")
if choice == '5':
print("Goodbye!")
break
if choice in ['1', '2', '3', '4']:
num1 = float(input("First number: "))
num2 = float(input("Second number: "))
if choice == '1':
print(f"Result: {num1 + num2}")
elif choice == '2':
print(f"Result: {num1 - num2}")
elif choice == '3':
print(f"Result: {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"Result: {num1 / num2}")
else:
print("Error: Cannot divide by zero!")
else:
print("Invalid choice! Please try again.")
๐ Fun Project: Mad Libs Game
Remember Mad Libs? Let's create a digital version:
# madlibs.py
print("Let's create a silly story together!")
print("I'll ask you for some words...\n")
# Collect words from the user
adjective1 = input("Give me an adjective (describing word): ")
noun1 = input("Give me a noun (person, place, or thing): ")
verb1 = input("Give me a verb ending in -ing: ")
adjective2 = input("Give me another adjective: ")
noun2 = input("Give me another noun: ")
number = input("Give me a number: ")
# Create the story
print("\n" + "="*50)
print("Here's your silly story:")
print("="*50 + "\n")
story = f"""
The {adjective1} {noun1} was {verb1} through the park
when suddenly a {adjective2} {noun2} appeared!
It had {number} eyes and was singing opera.
What a strange day at the park!
"""
print(story)
Sample Output:
Let's create a silly story together!
I'll ask you for some words...
Give me an adjective (describing word): sparkly
Give me a noun (person, place, or thing): dinosaur
Give me a verb ending in -ing: dancing
Give me another adjective: tiny
Give me another noun: pizza
Give me a number: 47
==================================================
Here's your silly story:
==================================================
The sparkly dinosaur was dancing through the park
when suddenly a tiny pizza appeared!
It had 47 eyes and was singing opera.
What a strange day at the park!
๐ Common Mistakes and Edge Cases
โ ๏ธ Mistake: Forgetting to convert numbers
# Wrong
age = input("Your age: ")
print("In 10 years you'll be " + age + 10) # Error!
# Right
age = input("Your age: ")
age = int(age)
print(f"In 10 years you'll be {age + 10}")
โ Pro tip: Combine input and conversion
# Instead of:
age = input("Your age: ")
age = int(age)
# You can write:
age = int(input("Your age: "))
๐ก๏ธ Handling Edge Cases
Always consider what could go wrong with user input:
# 1. Empty input
user_input = input("Enter something: ")
if user_input == "":
print("You didn't enter anything!")
# 2. Extra spaces
username = input("Username: ").strip() # Remove extra spaces
username = username.lower() # Normalize case
# 3. Yes/No questions
response = input("Continue? (y/n): ").lower().strip()
if response in ['y', 'yes', 'yeah', 'sure']:
print("Continuing...")
elif response in ['n', 'no', 'nope']:
print("Stopping...")
else:
print("Please answer yes or no")
๐ก๏ธ Input Validation Best Practices
Always validate user input to prevent errors:
# Safe input with validation
def get_integer(prompt):
"""Safely get an integer from user"""
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a valid number!")
# Use it
age = get_integer("Enter your age: ")
# Validate range
while True:
score = get_integer("Enter score (0-100): ")
if 0 <= score <= 100:
break
print("Score must be between 0 and 100!")
# Check for empty input
name = input("Enter your name: ").strip()
if not name:
name = "Anonymous"
๐๏ธ Practice Exercises
๐๏ธ Exercise 1: Personal Info Card
Objective: Get user input and display a formatted info card.
Instructions:
- Ask for user's name, age, and favorite color
- Calculate their birth year (approximately)
- Create a formatted "info card" display
๐ก Hint
To calculate birth year: 2026 - age. Use f-strings with alignment (:<15) to make the card look nice.
โ Solution
name = input("Enter your name: ")
age = int(input("Enter your age: "))
color = input("Enter your favorite color: ")
birth_year = 2026 - age
print("\n" + "=" * 30)
print(" ๐ INFO CARD")
print("=" * 30)
print(f" Name: {name}")
print(f" Age: {age}")
print(f" Born: ~{birth_year}")
print(f" Color: {color}")
print("=" * 30)
Sample Output:
==============================
๐ INFO CARD
==============================
Name: Alex
Age: 25
Born: ~2001
Color: teal
==============================
๐๏ธ Exercise 2: Restaurant Bill Calculator
Objective: Calculate a restaurant bill with tip.
Instructions:
- Ask for the meal cost
- Ask for the tip percentage
- Calculate the tip amount
- Show the total bill
๐ก Hint
Tip amount = meal cost ร (tip percentage / 100). Use :.2f for dollar formatting.
โ Solution
print("๐ฝ๏ธ Restaurant Bill Calculator")
print("-" * 30)
meal_cost = float(input("Enter the meal cost: $"))
tip_percent = float(input("Enter tip percentage: "))
tip_amount = meal_cost * (tip_percent / 100)
total = meal_cost + tip_amount
print(f"\nMeal cost: ${meal_cost:.2f}")
print(f"Tip ({tip_percent:.0f}%): ${tip_amount:.2f}")
print(f"Total: ${total:.2f}")
Sample Output:
๐ฝ๏ธ Restaurant Bill Calculator
------------------------------
Enter the meal cost: $45.50
Enter tip percentage: 20
Meal cost: $45.50
Tip (20%): $9.10
Total: $54.60
๐๏ธ Exercise 3: Adventure Game Start
Objective: Create the beginning of a text adventure using input.
Instructions:
- Ask for the player's name
- Ask for their character class (warrior, mage, rogue)
- Ask for their starting weapon
- Create an introduction story using their inputs
๐ก Hint
Use a multi-line f-string (f"""...""") to write the story. The .title() method capitalizes the first letter of each word.
โ Solution
print("โ๏ธ Welcome to the Adventure!")
print("=" * 35)
player_name = input("What is your name, adventurer? ")
char_class = input("Choose your class (warrior/mage/rogue): ")
weapon = input("What weapon do you carry? ")
story = f"""
โ๏ธ The Tale of {player_name.title()} โ๏ธ
In the ancient land of Pythonia, a brave {char_class}
named {player_name.title()} set forth on a great quest.
Armed with a trusty {weapon}, {player_name.title()} the
{char_class.title()} ventured into the unknown...
Your adventure begins now!
"""
print(story)
Sample Output:
โ๏ธ The Tale of Luna โ๏ธ
In the ancient land of Pythonia, a brave mage
named Luna set forth on a great quest.
Armed with a trusty enchanted staff, Luna the
Mage ventured into the unknown...
Your adventure begins now!
๐ฏ Quick Quiz
Question 1: What type of data does input() always return?
Question 2: What will this code produce?
num = input("Number: ") # User types: 5
print(num * 3)
Question 3: Which line correctly gets a decimal number from the user?
Summary
๐ Key Takeaways
input()makes your programs interactive- Input ALWAYS returns text (string), even for numbers
- Use
int()orfloat()to convert text to numbers - Good prompts help users know what to type
- You can combine multiple inputs to create interesting programs
- Always validate user input to prevent errors
๐ Real-World Applications
Input is everywhere in software: login screens (username and password), search bars (your search query), forms (contact info, surveys, applications), games (character names, choices, commands), and voice assistants ("Hey Siri" is just fancy input!).
๐ What's Next?
Now that our programs can have conversations, we'll learn how to make decisions based on user input. Get ready to teach Python how to think with if-statements!
๐ Congratulations!
Your programs can now talk and listen! You've unlocked the power of interactive programming. Try creating a "Choose Your Own Adventure" story where the user's input determines what happens next!