3.1 Making Decisions in Python

Welcome to Control Flow! This tutorial will teach you how to make decisions and create logic in your programs. You’ll learn how to write code that can choose different paths based on conditions.

3.2 What is Control Flow?

Control flow is how your program makes decisions. Instead of just running code line by line, you can make your program: - Execute code only when certain conditions are met - Choose between different options - Skip code that isn’t needed

Think of it like a flowchart where your code can take different paths!

3.3 Comparison Operators

Before we make decisions, we need to know how to compare values. Comparison operators let you test relationships between values and always return True or False.

The Comparison Operators

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
< Less than 3 < 5 True
> Greater than 5 > 3 True
<= Less than or equal to 5 <= 5 True
>= Greater than or equal to 5 >= 3 True

Comparison Examples

# Number comparisons
x = 10
y = 5

print(f"x = {x}, y = {y}")
print(f"x == y: {x == y}")  # Equal to
print(f"x != y: {x != y}")  # Not equal to
print(f"x > y: {x > y}")    # Greater than
print(f"x < y: {x < y}")    # Less than
print(f"x >= y: {x >= y}")  # Greater than or equal
print(f"x <= y: {x <= y}")  # Less than or equal
x = 10, y = 5
x == y: False
x != y: True
x > y: True
x < y: False
x >= y: True
x <= y: False
# String comparisons
name1 = "Alice"
name2 = "Bob"
name3 = "Alice"

print(f"\nString comparisons:")
print(f"'{name1}' == '{name2}': {name1 == name2}")
print(f"'{name1}' == '{name3}': {name1 == name3}")
print(f"'{name1}' != '{name2}': {name1 != name2}")

String comparisons:
'Alice' == 'Bob': False
'Alice' == 'Alice': True
'Alice' != 'Bob': True

Important: Use == for comparison and = for assignment!

# This is assignment (storing a value)
age = 25

# This is comparison (checking equality)
is_adult = age == 25
print(f"Is adult? {is_adult}")
Is adult? True

3.4 The if Statement

The if statement lets you run code only when a condition is true.

Syntax:

if condition:
    # code to run if condition is True
    # must be indented!

Basic if Examples

# Simple if statement
temperature = 30

if temperature > 25:
    print("It's hot outside! 🌞")
    print("Don't forget sunscreen!")
It's hot outside! 🌞
Don't forget sunscreen!
# Another example
age = 18

if age >= 18:
    print("You are an adult!")
    print("You can vote!")
You are an adult!
You can vote!
# Example where condition is False
score = 45

if score >= 50:
    print("You passed!")  # This won't print because condition is False

print("Test complete")  # This always prints (not indented under if)
Test complete

Key Points: - The condition must end with a colon : - The code to run must be indented (usually 4 spaces) - If the condition is False, the indented code is skipped

3.5 The else Statement

The else statement provides an alternative when the if condition is False.

Syntax:

if condition:
    # runs if condition is True
else:
    # runs if condition is False

if-else Examples

# Simple if-else
age = 15

if age >= 18:
    print("You can vote!")
else:
    print("You're too young to vote.")
    years_until_voting = 18 - age
    print(f"Wait {years_until_voting} more years.")
You're too young to vote.
Wait 3 more years.
# Checking even or odd numbers
number = 7

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")
7 is odd
# Password checker
password = "python123"

if len(password) >= 8:
    print("✅ Password is strong enough")
else:
    print("❌ Password is too short")
    print(f"   Add {8 - len(password)} more characters")
✅ Password is strong enough

3.6 The elif Statement

elif (short for “else if”) lets you check multiple conditions in sequence. It’s like saying “if not that, then check this instead.”

Syntax:

if condition1:
    # runs if condition1 is True
elif condition2:
    # runs if condition1 is False and condition2 is True
else:
    # runs if all conditions are False

elif Examples

# Grade calculator
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}")
print(f"Grade: {grade}")
Score: 85
Grade: B
# Temperature description
temp = 15

if temp > 30:
    description = "very hot"
    emoji = "🥵"
elif temp > 20:
    description = "warm"
    emoji = "😊"
elif temp > 10:
    description = "cool"
    emoji = "😌"
elif temp > 0:
    description = "cold"
    emoji = "🥶"
else:
    description = "freezing"
    emoji = "🧊"

print(f"It's {description} at {temp}°C {emoji}")
It's cool at 15°C 😌
# Time of day greeting
hour = 14

if hour < 12:
    greeting = "Good morning!"
elif hour < 18:
    greeting = "Good afternoon!"
else:
    greeting = "Good evening!"

print(greeting)
Good afternoon!

Important: Python checks conditions in order and stops at the first True condition!

# Demonstrating order matters
x = 15

# This works correctly
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5")  # Won't reach here even though it's true!
x is greater than 10

3.7 Logical Operators

You can combine multiple conditions using logical operators:

Operator Meaning Example
and Both must be True age >= 18 and has_license
or At least one must be True is_weekend or is_holiday
not Reverses the condition not is_raining

Logical Operator Examples

# Using 'and' - both conditions must be True
age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("✅ You can enter the concert!")
else:
    print("❌ You cannot enter")
✅ You can enter the concert!
# More 'and' examples
temperature = 25
is_sunny = True

if temperature > 20 and is_sunny:
    print("Perfect day for the beach! 🏖️")
Perfect day for the beach! 🏖️
# Using 'or' - at least one condition must be True
day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend! 🎉")
else:
    print("It's a weekday 😴")
It's the weekend! 🎉
# Using 'not' - reverses the boolean
is_raining = False

if not is_raining:
    print("Let's go outside!")
else:
    print("Let's stay inside")
Let's go outside!
# Combining multiple logical operators
age = 25
is_student = True
has_id = True

if age >= 18 and (is_student or age >= 65) and has_id:
    print("✅ You qualify for a discount!")
    if is_student:
        discount = 20
    else:
        discount = 15
    print(f"Your discount: {discount}%")
else:
    print("Regular price applies")
✅ You qualify for a discount!
Your discount: 20%

3.8 Nested if Statements

You can put if statements inside other if statements. This is called nesting.

# Nested if example
has_account = True
balance = 150
purchase_amount = 100

if has_account:
    print("Account found")

    if balance >= purchase_amount:
        balance = balance - purchase_amount
        print(f"✅ Purchase successful!")
        print(f"Remaining balance: ${balance}")
    else:
        print("❌ Insufficient funds")
        print(f"You need ${purchase_amount - balance} more")
else:
    print("❌ No account found")
Account found
✅ Purchase successful!
Remaining balance: $50
# Another nested example
age = 25
has_license = True
has_car = False

if age >= 18:
    print("Age requirement met")

    if has_license:
        print("License verified")

        if has_car:
            print("✅ You can drive!")
        else:
            print("⚠️ You need to rent a car")
    else:
        print("❌ You need a license")
else:
    print("❌ You must be 18 or older")
Age requirement met
License verified
⚠️ You need to rent a car

Tip: Try to avoid too many nested levels. It makes code harder to read. Often you can use and instead:

# Instead of deeply nested ifs, use 'and'
age = 25
has_license = True
has_car = True

# Clear and readable
if age >= 18 and has_license and has_car:
    print("✅ You can drive!")
else:
    print("❌ Requirements not met")
✅ You can drive!

3.9 The Membership Operator ‘in’

The in operator checks if a value exists in a sequence (like a string or list).

# Check if character is in string
word = "Python"

if "y" in word:
    print("Found 'y' in Python")

if "x" in word:
    print("Found 'x'")
else:
    print("'x' is not in Python")
Found 'y' in Python
'x' is not in Python
# Check if item is in a list
fruits = ["apple", "banana", "orange"]

if "banana" in fruits:
    print("We have bananas! 🍌")

if "grape" not in fruits:
    print("Sorry, no grapes available")
We have bananas! 🍌
Sorry, no grapes available
# Using 'in' with if-elif-else
user_input = "yes"

if user_input in ["yes", "y", "Yeah", "sure"]:
    print("Great! Let's proceed.")
elif user_input in ["no", "n", "nope"]:
    print("Okay, maybe next time.")
else:
    print("I didn't understand that.")
Great! Let's proceed.

3.10 Ternary Operator (Conditional Expression)

Python has a shorthand way to write simple if-else statements in one line.

Syntax:

value_if_true if condition else value_if_false
# Regular if-else
age = 20
if age >= 18:
    status = "adult"
else:
    status = "minor"
print(status)

# Same thing with ternary operator
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
adult
adult
# More ternary examples
temperature = 28
weather = "hot" if temperature > 25 else "comfortable"
print(f"It's {weather}")

score = 85
result = "Pass" if score >= 50 else "Fail"
print(f"Result: {result}")

number = 7
parity = "even" if number % 2 == 0 else "odd"
print(f"{number} is {parity}")
It's hot
Result: Pass
7 is odd

When to use: Ternary operators are great for simple conditions, but use regular if-else for complex logic!

3.11 Real-World Examples

Example 1: Login System

# Simple login validator
username = "alice"
password = "secret123"

correct_username = "alice"
correct_password = "secret123"

if username == correct_username and password == correct_password:
    print("✅ Login successful!")
    print(f"Welcome back, {username}!")
elif username == correct_username:
    print("❌ Incorrect password")
else:
    print("❌ Username not found")
✅ Login successful!
Welcome back, alice!

Example 2: Shipping Calculator

# Calculate shipping cost based on weight and destination
weight = 5  # kg
destination = "international"

if destination == "local":
    if weight <= 1:
        shipping_cost = 5
    elif weight <= 5:
        shipping_cost = 10
    else:
        shipping_cost = 15
elif destination == "international":
    if weight <= 1:
        shipping_cost = 20
    elif weight <= 5:
        shipping_cost = 40
    else:
        shipping_cost = 60
else:
    shipping_cost = 0
    print("Invalid destination")

if shipping_cost > 0:
    print(f"Weight: {weight}kg")
    print(f"Destination: {destination}")
    print(f"Shipping cost: ${shipping_cost}")
Weight: 5kg
Destination: international
Shipping cost: $40

Example 3: BMI Calculator

# Body Mass Index calculator with interpretation
weight_kg = 70
height_m = 1.75

bmi = weight_kg / (height_m ** 2)
print(f"Your BMI: {bmi:.1f}")

if bmi < 18.5:
    category = "Underweight"
    emoji = "⚠️"
elif bmi < 25:
    category = "Normal weight"
    emoji = "✅"
elif bmi < 30:
    category = "Overweight"
    emoji = "⚠️"
else:
    category = "Obese"
    emoji = "🚨"

print(f"{emoji} Category: {category}")
Your BMI: 22.9
✅ Category: Normal weight

3.12 Common Mistakes to Avoid

Mistake 1: Forgetting the colon

# Wrong - missing colon
if age >= 18
    print("Adult")

# Correct
if age >= 18:
    print("Adult")

Mistake 2: Incorrect indentation

# Wrong - not indented
if age >= 18:
print("Adult")

# Correct
if age >= 18:
    print("Adult")

Mistake 3: Using = instead of ==

# Wrong - this is assignment, not comparison
if age = 18:
    print("Adult")

# Correct
if age == 18:
    print("Adult")

Mistake 4: Comparing different types

# Be careful with types!
age_str = "18"  # This is a string
age_num = 18    # This is a number

print(age_str == age_num)  # False! Different types

# Solution: convert types
print(int(age_str) == age_num)  # True!
False
True

3.13 Practice Exercises

Now it’s your turn! Try these exercises:

Exercise 1: Number Classifier

Write code to classify a number as positive, negative, or zero.

number = -5
# Your code here:
# Print whether the number is positive, negative, or zero

Exercise 2: Ticket Price Calculator

Calculate ticket prices based on age: - Under 3: Free - 3-12: $10 - 13-64: $25 - 65+: $15

age = 8
# Your code here:
# Calculate and print the ticket price

Exercise 3: Leap Year Checker

A year is a leap year if: - It’s divisible by 4 AND - If it’s divisible by 100, it must also be divisible by 400

year = 2024
# Your code here:
# Print whether it's a leap year or not

Exercise 4: Grade with Plus/Minus

Expand the grade calculator to include + and - grades: - 93-100: A - 90-92: A- - 87-89: B+ - 83-86: B - 80-82: B- - etc.

score = 87
# Your code here:
# Print the grade with + or -

3.14 Solutions

Solution 1: Number Classifier

Click to show solution
number = -5

if number > 0:
    print(f"{number} is positive")
elif number < 0:
    print(f"{number} is negative")
else:
    print(f"{number} is zero")
-5 is negative

Solution 2: Ticket Price Calculator

Click to show solution
age = 8

if age < 3:
    price = 0
    print(f"Age {age}: Free!")
elif age <= 12:
    price = 10
    print(f"Age {age}: Child ticket - ${price}")
elif age <= 64:
    price = 25
    print(f"Age {age}: Adult ticket - ${price}")
else:
    price = 15
    print(f"Age {age}: Senior ticket - ${price}")
Age 8: Child ticket - $10

Solution 3: Leap Year Checker

Click to show solution
year = 2024

if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print(f"{year} is a leap year! 🎉")
        else:
            print(f"{year} is not a leap year")
    else:
        print(f"{year} is a leap year! 🎉")
else:
    print(f"{year} is not a leap year")

# Alternative solution using 'and'/'or'
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year! 🎉")
else:
    print(f"{year} is not a leap year")
2024 is a leap year! 🎉
2024 is a leap year! 🎉

Solution 4: Grade with Plus/Minus

Click to show solution
score = 87

if score >= 93:
    grade = "A"
elif score >= 90:
    grade = "A-"
elif score >= 87:
    grade = "B+"
elif score >= 83:
    grade = "B"
elif score >= 80:
    grade = "B-"
elif score >= 77:
    grade = "C+"
elif score >= 73:
    grade = "C"
elif score >= 70:
    grade = "C-"
elif score >= 67:
    grade = "D+"
elif score >= 63:
    grade = "D"
elif score >= 60:
    grade = "D-"
else:
    grade = "F"

print(f"Score: {score} = Grade: {grade}")
Score: 87 = Grade: B+

3.15 Key Takeaways

✨ Remember:

  1. Comparison Operators: Use ==, !=, <, >, <=, >= to compare values
  2. if statement: Runs code only when condition is True
  3. else statement: Provides alternative when condition is False
  4. elif statement: Checks multiple conditions in sequence
  5. Logical operators: Use and, or, not to combine conditions
  6. Indentation matters: Code blocks must be properly indented
  7. Order matters: Python checks conditions from top to bottom
  8. Use == for comparison, = for assignment

3.16 Quick Reference Card

# Basic if
if condition:
    # code

# if-else
if condition:
    # code
else:
    # code

# if-elif-else
if condition1:
    # code
elif condition2:
    # code
else:
    # code

# Logical operators
if condition1 and condition2:  # Both must be True
if condition1 or condition2:   # At least one must be True
if not condition:              # Reverse the condition

# Ternary
value = true_result if condition else false_result

3.17 Next Steps

Now that you understand control flow, you’re ready to learn: - Loops - Repeating code with for and while - Functions - Organizing code into reusable blocks - Lists and Dictionaries - Working with collections of data - Error handling - Using try/except blocks

Keep practicing! The more you write conditional statements, the more natural they’ll become. Control flow is fundamental to all programming! 🚀