đ¤ 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, andelsestatements to control program flow - Use comparison operators (
==,!=,>,<,>=,<=) - Combine conditions with
and,or, andnot - 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!
đ 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:
â ī¸ 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 |
|---|---|---|---|
== | Equals | 5 == 5 | True |
!= | Not equals | 5 != 3 | True |
> | Greater than | 10 > 3 | True |
< | Less than | 2 < 7 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 3 <= 8 | True |
# 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-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
đ 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
| A | B | A and B |
|---|---|---|
| True | True | True â |
| True | False | False â |
| False | True | False â |
| False | False | False â |
| A | B | A or B |
|---|---|---|
| True | True | True â |
| True | False | True â |
| False | True | True â |
| False | False | False â |
đĸ 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()
đ 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:
- Ask for the temperature
- Give clothing advice based on temperature ranges
- 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:
- Store a username and password
- Ask user for credentials
- Give different messages for wrong username vs wrong password
- 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:
- Ask for age and day of week
- 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
eliflets you check multiple conditions in orderand,or,notlet 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!