Skip to main content

🤔 Lesson 5: Making Decisions with If-Statements

So far, our programs have been like trains on a track — they go straight from start to finish. Now we'll teach them to make decisions, like choosing which path to take at a fork in the road!

đŸŽ¯ Learning Objectives

By the end of this lesson, you will be able to:

  • Write if, elif, and else statements to control program flow
  • Use comparison operators (==, !=, >, <, >=, <=)
  • Combine conditions with and, or, and not
  • Understand how indentation defines code blocks
  • Nest if-statements for complex decision-making

Estimated Time: 45–60 minutes

Project: Build a theme park ride eligibility checker and a movie ticket pricing system

In This Lesson

🧠 Teaching Python to Think

Every day you make hundreds of decisions: "If it's raining, I'll take an umbrella." Now you'll teach Python to do the same!

graph TD A["đŸŒ¤ī¸ Start"] --> B{"đŸŒ§ī¸ Is it raining?"} B -->|"Yes"| C["â˜‚ī¸ Take umbrella"] B -->|"No"| D["😎 Wear sunglasses"] C --> E["đŸšļ Go outside"] D --> E

📝 The Basic If-Statement

An if-statement is Python's way of saying "IF this is true, THEN do this":

# Basic if-statement structure
age = 18
if age >= 18:
    print("You can vote!")
    print("You're an adult!")

print("This always prints")  # Not indented, so not part of the if

The Magic of Indentation

Python uses indentation (spaces at the beginning of lines) to group code together. It's like putting things in a box:

if temperature > 30: print("It's hot!") print("Drink water!") print("Stay in shade!") Inside if print("Have a nice day!") Always runs âŦ†ī¸ Indented lines run only if the condition is True
Figure 1: Indentation tells Python which lines belong inside the if-statement.

âš ī¸ Watch Out

Python is strict about indentation! Use 4 spaces (or 1 tab) consistently. Mixing spaces and tabs will cause an IndentationError.

âš–ī¸ Comparison Operators

To make decisions, Python needs to compare things. Here are the tools:

Operator Meaning Example Result
==Equals5 == 5True
!=Not equals5 != 3True
>Greater than10 > 3True
<Less than2 < 7True
>=Greater or equal5 >= 5True
<=Less or equal3 <= 8True
# Comparison operators in action
score = 85

if score == 100:
    print("Perfect score!")

if score >= 90:
    print("A grade!")

if score < 60:
    print("Need more practice")

📖 Key Difference

= means assign a value (x = 5 stores 5 in x). == means compare two values (x == 5 checks if x equals 5). This is one of the most common beginner mistakes!

â†”ī¸ If-Else: The Either-Or Decision

Sometimes you want to do one thing OR another:

password = input("Enter password: ")

if password == "secret123":
    print("Access granted!")
    print("Welcome to the system")
else:
    print("Access denied!")
    print("Wrong password")
🔀 If-Else Flow Condition True ✅ if block Do this False ❌ else block Do that
Figure 2: The if-else pattern — Python always takes exactly one of the two paths.

đŸ”ĸ If-Elif-Else: Multiple Choices

What if you have more than two options? That's where elif (else if) comes in:

grade = int(input("Enter your grade (0-100): "))

if grade >= 90:
    print("A - Excellent!")
elif grade >= 80:
    print("B - Good job!")
elif grade >= 70:
    print("C - Satisfactory")
elif grade >= 60:
    print("D - Needs improvement")
else:
    print("F - Please see teacher")

# Python checks each condition in order
# Once it finds a true condition, it stops checking
graph TD A["📊 Check Grade"] --> B{"grade >= 90?"} B -->|"Yes"| C["đŸ…°ī¸ A - Excellent!"] B -->|"No"| D{"grade >= 80?"} D -->|"Yes"| E["đŸ…ąī¸ B - Good job!"] D -->|"No"| F{"grade >= 70?"} F -->|"Yes"| G["ÂŠī¸ C - Satisfactory"] F -->|"No"| H{"grade >= 60?"} H -->|"Yes"| I["đŸ…ŗ D - Needs improvement"] H -->|"No"| J["đŸ…ĩ F - Please see teacher"]

🆕 Modern Alternative: Match-Case (Python 3.10+)

Python 3.10 introduced match-case statements for cleaner multiple-choice logic:

# Traditional if-elif-else
command = input("Enter command: ").lower()
if command == "start":
    print("Starting...")
elif command == "stop":
    print("Stopping...")
elif command == "pause":
    print("Pausing...")
else:
    print("Unknown command")

# Modern match-case (Python 3.10+)
match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case "pause":
        print("Pausing...")
    case _:  # Default case
        print("Unknown command")

🔗 Combining Conditions

Sometimes you need to check multiple things at once:

# Using 'and' - both must be true
age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")

# Using 'or' - at least one must be true
day = "Saturday"
holiday = False

if day == "Saturday" or day == "Sunday" or holiday:
    print("No work today!")

# Using 'not' - reverses true/false
raining = False

if not raining:
    print("Great weather for a picnic!")

📊 Truth Tables for Logical Operators

AND Operator (both must be True)
ABA and B
TrueTrueTrue ✅
TrueFalseFalse ❌
FalseTrueFalse ❌
FalseFalseFalse ❌
OR Operator (at least one must be True)
ABA or B
TrueTrueTrue ✅
TrueFalseTrue ✅
FalseTrueTrue ✅
FalseFalseFalse ❌

đŸŽĸ Real-World Example: Theme Park Ride

Let's build a program that checks if someone can ride a roller coaster:

# Roller Coaster Safety Check
print("Welcome to the Thunder Mountain Roller Coaster!")
print("-" * 40)

height = float(input("Enter your height in cm: "))
age = int(input("Enter your age: "))
has_adult = input("Are you with an adult? (yes/no): ").lower()

# Check eligibility
if height < 120:
    print("\nSorry, you're too short for this ride.")
    print("Try the kiddie coaster instead!")
elif height >= 120 and age >= 12:
    print("\nYou can ride! Enjoy!")
elif height >= 120 and age >= 8 and has_adult == "yes":
    print("\nYou can ride with adult supervision!")
else:
    print("\nSorry, you don't meet the requirements.")
    print("You need to be 12+ or 8+ with an adult.")

đŸĒ† Nested If-Statements

You can put if-statements inside other if-statements, like Russian dolls:

# ATM simulation
pin = input("Enter PIN: ")

if pin == "1234":
    print("PIN correct!")
    action = input("Withdraw or Check Balance? (w/c): ").lower()

    if action == "w":
        amount = float(input("How much to withdraw? $"))
        balance = 1000  # Pretend balance

        if amount <= balance:
            print(f"Dispensing ${amount}")
            print(f"New balance: ${balance - amount}")
        else:
            print("Insufficient funds!")

    elif action == "c":
        print("Your balance is: $1000")
    else:
        print("Invalid option")
else:
    print("Incorrect PIN!")

✅ Managing Complex Nested Conditions

Tips for handling complex nested logic:

# Instead of deep nesting:
if condition1:
    if condition2:
        if condition3:
            do_something()

# Combine conditions:
if condition1 and condition2 and condition3:
    do_something()

# Or use early exits (in functions):
def check_all():
    if not condition1:
        return
    if not condition2:
        return
    if not condition3:
        return
    do_something()
graph TD A["đŸ—ī¸ Common If-Statement Patterns"] --> B["✅ Validation"] A --> C["📊 Range Checking"] A --> D["📋 Menu Selection"] A --> E["🔐 Access Control"] B --> F["Is input valid?"] C --> G["Is value in range?"] D --> H["Which option picked?"] E --> I["Is user authorized?"]

🐛 Common Mistakes to Avoid

âš ī¸ Mistake 1: Using = instead of ==

# Wrong - this assigns 5 to x!
# if x = 5:    # SyntaxError!

# Right - this compares x to 5
if x == 5:
    print("x is 5")

âš ī¸ Mistake 2: Forgetting the colon

# Wrong
# if score > 90     # SyntaxError!
#     print("Great!")

# Right
if score > 90:
    print("Great!")

✅ Pro Tip

When writing if-elif-else chains, put the most specific conditions first. Python stops checking once it finds a true condition, so order matters!

📖 Real-Life Analogy

If-statements are like the decisions you make every day: Morning routine — IF alarm rings, THEN get up, ELSE sleep more. Crossing street — IF light is green, THEN walk, ELSE wait. Cooking — IF water boiling, THEN add pasta. Phone — IF battery < 20%, THEN charge phone.

đŸ‹ī¸ Practice Exercises

đŸ‹ī¸ Exercise 1: Temperature Advisor

Objective: Give clothing advice based on temperature.

Instructions:

  1. Ask for the temperature
  2. Give clothing advice based on temperature ranges
  3. Warn about extreme temperatures
💡 Hint

Use elif chains: below 32°F → freezing warning, 32–50 → heavy coat, 50–70 → light jacket, 70–85 → t-shirt, above 85 → heat warning.

✅ Solution
temp = float(input("Enter temperature (°F): "))

if temp < 32:
    print("đŸĨļ FREEZING! Stay indoors if possible!")
    print("Wear heavy coat, gloves, and hat")
elif temp < 50:
    print("đŸ§Ĩ Cold — wear a heavy coat")
elif temp < 70:
    print("đŸ§Ŗ Cool — a light jacket will do")
elif temp < 85:
    print("👕 Nice weather — t-shirt time!")
else:
    print("đŸ”Ĩ HOT! Stay hydrated!")
    print("Wear light clothing and sunscreen")

đŸ‹ī¸ Exercise 2: Simple Login System

Objective: Build a login checker with specific error messages.

Instructions:

  1. Store a username and password
  2. Ask user for credentials
  3. Give different messages for wrong username vs wrong password
  4. Welcome user on successful login
💡 Hint

Check username first with an outer if, then check password inside with a nested if.

✅ Solution
STORED_USER = "admin"
STORED_PASS = "python123"

username = input("Username: ")
password = input("Password: ")

if username == STORED_USER:
    if password == STORED_PASS:
        print(f"✅ Welcome, {username}!")
    else:
        print("❌ Wrong password!")
else:
    print("❌ Username not found!")

đŸ‹ī¸ Exercise 3: Movie Ticket Pricing

Objective: Calculate ticket price based on age and day of week.

Instructions:

  1. Ask for age and day of week
  2. Apply discounts: children (under 12) $8, seniors (65+) $9, Tuesday discount $10 for everyone, regular price $15
💡 Hint

Check Tuesday first (it overrides age-based pricing), then check age ranges with elif.

✅ Solution
age = int(input("Enter your age: "))
day = input("What day is it? ").lower().strip()

if day == "tuesday":
    price = 10
    print("đŸŽŦ Tuesday special!")
elif age < 12:
    price = 8
    print("🧒 Child discount!")
elif age >= 65:
    price = 9
    print("👴 Senior discount!")
else:
    price = 15

print(f"Your ticket price: ${price}")

Sample Output:

Enter your age: 10
What day is it? friday
🧒 Child discount!
Your ticket price: $8

đŸŽ¯ Quick Quiz

Question 1: What does the == operator do in Python?

Question 2: What prints when this code runs?

x = 15
if x > 20:
    print("A")
elif x > 10:
    print("B")
elif x > 5:
    print("C")
else:
    print("D")

Question 3: What does not True evaluate to?

Summary

🎉 Key Takeaways

  • If-statements let programs make decisions
  • Use == for comparison, = for assignment
  • Indentation shows what code belongs to the if-statement
  • elif lets you check multiple conditions in order
  • and, or, not let you combine conditions
  • You can nest if-statements inside each other

🚀 What's Next?

Now that Python can make decisions, we'll learn about loops — how to make Python repeat tasks. Imagine not having to copy-paste code 100 times!

🎉 Congratulations!

Your programs can now think and choose! Conditional logic is one of the most powerful concepts in programming — every app, game, and website uses it constantly. You're building real skills!