Control Flow: Making Decisions and Creating Loops
Welcome to the world of smart programming! So far you’ve learned how to store data and perform basic operations. Now it’s time to make your programs think and decide for themselves.
What is Control Flow?
Control flow is like being the director of a play. You decide:
- What happens next based on current conditions
- When to repeat actions
- How to handle different situations
Imagine you’re cooking pasta:
- If the water is boiling → add pasta
- While the pasta is cooking → stir occasionally
- For each minute of cooking → check if it’s done
That’s control flow in action!
Method 1: Conditional Statements (if-else) - Like Decision Making
The Restaurant Decision Analogy
Imagine you’re at a restaurant deciding what to order:
hungry = True
has_money = True
is_vegetarian = False
if hungry and has_money:
if is_vegetarian:
print("I'll order a vegetable stir-fry!")
else:
print("I'll order chicken curry!")
else:
print("Maybe just coffee for now.")
Basic if Statement
The if statement is like asking “Should I do this?“
age = 18
if age >= 18:
print("You can vote!")
print("You can drive!")
print("You can get a tattoo!")
print("This always prints") # Not indented, so always runs
if-else Statement
The else is like saying “If not this, then that.”
temperature = 25
if temperature > 30:
print("It's hot! Turn on the AC.")
print("Drink cold water.")
else:
print("Nice weather!")
print("Perfect for a walk.")
print("Weather check complete.")
if-elif-else Chain
elif means “else if” - for multiple conditions.
score = 85
if score >= 90:
print("Grade: A - Excellent!")
elif score >= 80:
print("Grade: B - Good job!")
elif score >= 70:
print("Grade: C - Satisfactory")
elif score >= 60:
print("Grade: D - Needs improvement")
else:
print("Grade: F - Try again")
print("Grading complete.")
Nested if Statements
You can put if statements inside other if statements.
has_ticket = True
age = 16
with_parent = True
if has_ticket:
if age >= 18:
print("Welcome! Full price ticket.")
elif age >= 13:
print("Welcome! Teen ticket.")
else:
if with_parent:
print("Welcome! Child ticket with parent.")
else:
print("Sorry, children under 13 need a parent.")
else:
print("Please buy a ticket first.")
Method 2: Loops (while and for) - Like Repeating Actions
The Exercise Routine Analogy
Imagine your morning exercise routine:
While loop: Keep running until you’re tired For loop: Do 10 push-ups, then 10 sit-ups, then 10 jumping jacks
while Loop - Repeat Until Condition is False
# Count down from 10
countdown = 10
while countdown > 0:
print(f"Countdown: {countdown}")
countdown = countdown - 1 # Or: countdown -= 1
print("Blast off! 🚀")
Infinite Loops (Careful!)
# This will run forever! (Don't run this)
# while True:
# print("This never stops!")
# Safe version with break
attempts = 0
while True:
password = input("Enter password: ")
if password == "secret123":
print("Access granted!")
break # Exit the loop
else:
attempts += 1
if attempts >= 3:
print("Too many attempts. Account locked.")
break
print("Wrong password. Try again.")
for Loop - Repeat for Each Item
# Loop through a list
fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
print(f"I like {fruit}s!")
print("All fruits listed!")
range() Function with for Loops
# Count from 1 to 5
for number in range(1, 6): # range(start, end) - end is exclusive
print(f"Number: {number}")
print()
# Count by 2s
for even in range(0, 11, 2): # range(start, end, step)
print(f"Even number: {even}")
print()
# Count backwards
for count in range(10, 0, -1):
print(f"Countdown: {count}")
print("Done!")
Method 3: Loop Control Statements
break - Exit the Loop Immediately
# Find the first even number
numbers = [1, 3, 5, 6, 8, 9, 10]
for num in numbers:
if num % 2 == 0: # If even
print(f"Found first even number: {num}")
break # Exit the loop
print(f"Checking: {num} (odd)")
print("Loop ended.")
continue - Skip to Next Iteration
# Print only odd numbers, skip even ones
for num in range(1, 11):
if num % 2 == 0: # If even
continue # Skip to next number
print(f"Odd number: {num}")
print("All odd numbers printed.")
else with Loops
# Check if number is prime
number = 17
is_prime = True
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
is_prime = False
break
if is_prime:
print(f"{number} is a prime number!")
else:
print(f"{number} is not a prime number.")
# Using else with for loop
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
print(f"{number} is divisible by {divisor}")
break
else: # This runs only if break was never called
print(f"{number} is a prime number!")
Real-World Examples
Example 1: Simple Calculator
print("Simple Calculator")
print("Operations: +, -, *, /")
print("Type 'quit' to exit")
while True:
operation = input("Enter operation (+, -, *, /) or 'quit': ")
if operation.lower() == 'quit':
print("Goodbye!")
break
if operation not in ['+', '-', '*', '/']:
print("Invalid operation. Try again.")
continue
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 == 0:
print("Cannot divide by zero!")
continue
result = num1 / num2
print(f"Result: {num1} {operation} {num2} = {result}")
except ValueError:
print("Please enter valid numbers.")
continue
print() # Empty line for readability
Example 2: Number Guessing Game
import random
print("🎯 Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Generate random number
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts + 1}/{max_attempts}. Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low! Try higher. 📈")
elif guess > secret_number:
print("Too high! Try lower. 📉")
else:
print(f"🎉 Congratulations! You got it in {attempts} attempts!")
break
except ValueError:
print("Please enter a valid number.")
continue
else: # This runs if the loop completed without break
print(f"😅 Game over! The number was {secret_number}.")
print("Thanks for playing!")
Example 3: Simple Menu System
def show_menu():
print("\n🍕 Pizza Restaurant Menu")
print("1. View Menu")
print("2. Order Pizza")
print("3. Check Order Status")
print("4. Exit")
print("-" * 30)
def show_pizza_menu():
print("\n🍕 Available Pizzas:")
print("1. Margherita - $12")
print("2. Pepperoni - $15")
print("3. Hawaiian - $16")
print("4. Veggie - $14")
# Main program
order_placed = False
current_order = None
while True:
show_menu()
choice = input("Enter your choice (1-4): ")
if choice == '1':
show_pizza_menu()
elif choice == '2':
show_pizza_menu()
pizza_choice = input("Enter pizza number (1-4): ")
pizza_menu = {
'1': ('Margherita', 12),
'2': ('Pepperoni', 15),
'3': ('Hawaiian', 16),
'4': ('Veggie', 14)
}
if pizza_choice in pizza_menu:
pizza_name, price = pizza_menu[pizza_choice]
current_order = f"{pizza_name} Pizza - ${price}"
order_placed = True
print(f"✅ Order placed: {current_order}")
else:
print("❌ Invalid pizza choice.")
elif choice == '3':
if order_placed and current_order:
print(f"📦 Your order: {current_order}")
print("Status: Being prepared... (Ready in 20 minutes)")
else:
print("📦 No active orders.")
elif choice == '4':
if order_placed:
print(f"Thanks for your order: {current_order}")
print("👋 Goodbye! Have a great day!")
break
else:
print("❌ Invalid choice. Please try again.")
Common Mistakes to Avoid
1. Infinite Loops
# ❌ Wrong - this will run forever
# while True:
# print("Stuck!")
# ✅ Correct - proper exit condition
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
2. Off-by-One Errors
# ❌ Wrong - range(1, 10) goes from 1 to 9
# for i in range(1, 10):
# print(i) # Prints 1, 2, 3, 4, 5, 6, 7, 8, 9
# ✅ Correct - range(1, 11) goes from 1 to 10
for i in range(1, 11):
print(i) # Prints 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
3. Forgetting to Update Loop Variables
# ❌ Wrong - i never changes
# i = 0
# while i < 5:
# print(i)
# ✅ Correct - update the variable
i = 0
while i < 5:
print(i)
i += 1
Practice Exercises
Exercise 1: Temperature Converter
Create a program that converts between Celsius and Fahrenheit with a menu.
Exercise 2: Simple ATM Simulator
Create a simple ATM that allows deposits, withdrawals, and balance checks.
Exercise 3: Multiplication Table Generator
Ask the user for a number and print its multiplication table (1-10).
Exercise 4: Password Validator
Create a password validator that checks:
- At least 8 characters
- Contains uppercase and lowercase letters
- Contains at least one number
Exercise 5: Rock-Paper-Scissors Game
Create a rock-paper-scissors game against the computer.
Summary
Control flow gives your programs the power to:
- Make decisions with
if-elif-else - Repeat actions with
whileandforloops - Handle different situations gracefully
- Create interactive programs that respond to user input
Remember:
ifchecks conditionswhilerepeats until a condition is falseforrepeats for each item in a sequencebreakexits loops immediatelycontinueskips to the next iteration
Next up: Functions - the building blocks of reusable code! 🚀