Skip to main content

๐Ÿ’ฌ 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() and float()
  • 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!

graph LR A["โŒจ๏ธ User Types Input"] --> B["๐Ÿ Python Receives It"] B --> C["โš™๏ธ Python Processes It"] C --> D["๐Ÿ“ค Python Responds"] D --> E["๐Ÿ‘€ User Sees Output"]

โœจ 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!")
๐Ÿ”„ How input() Works Display Prompt User Types Store in Variable name = input("Enter name: ") # User types: Alice # name now contains "Alice"
Figure 1: The 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:

๐Ÿ”ง Type Conversion Functions int() Text โ†’ Whole number int("42") โ†’ 42 float() Text โ†’ Decimal number float("3.14") โ†’ 3.14 str() Number โ†’ Text str(42) โ†’ "42" bool() Anything โ†’ True/False bool("yes") โ†’ True โš ๏ธ Warning: Conversion can fail! int("hello") will cause a ValueError ๐Ÿ’ก Shortcut: age = int(input("Your age: ")) โ€” combine input + conversion in one line!
Figure 2: Use these functions to convert user input to the type you need.
# 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"
graph TD A["๐Ÿง‘ User Types Input"] --> B{"Valid?"} B -->|"Yes โœ…"| C["โœ… Process Data"] B -->|"No โŒ"| D["โš ๏ธ Show Error Message"] D --> A C --> E["๐Ÿ“ค Show Result"]

๐Ÿ‹๏ธ Practice Exercises

๐Ÿ‹๏ธ Exercise 1: Personal Info Card

Objective: Get user input and display a formatted info card.

Instructions:

  1. Ask for user's name, age, and favorite color
  2. Calculate their birth year (approximately)
  3. 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:

  1. Ask for the meal cost
  2. Ask for the tip percentage
  3. Calculate the tip amount
  4. 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:

  1. Ask for the player's name
  2. Ask for their character class (warrior, mage, rogue)
  3. Ask for their starting weapon
  4. 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() or float() 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!