Control Flow
Control flow lets your code make decisions and repeat tasks. Master if statements and loops to build programs that adapt to different situations and handle repetitive work automatically.
Estimated reading time: 20 minutes
Control Flow at a Glance
- if/elif/else → make decisions based on conditions
- for → loop through lists, ranges, or sequences
- while → repeat while condition is True
- and/or/not → combine multiple conditions
Tip: Order conditions from most specific to most general.
Common Pitfalls
- Infinite loops → always ensure while conditions can become False
- Deep nesting → use logical operators to flatten conditions
- Wrong order → check specific cases before general ones
- Missing else → consider what happens when no conditions match
Rule: Keep conditions simple and readable for easier debugging.
If Statements
Make decisions based on conditions. The first True condition wins.
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")Comparison Operators
==equal to!=not equal to>greater than<less than>=greater than or equal to<=less than or equal to
Logical Operators
Combine multiple conditions with and, or, and not.
age = 25
has_license = True
if age >= 18 and has_license:
print("Can drive")
if age < 18 or not has_license:
print("Cannot drive")For Loops
Repeat code for each item in a sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# With index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")While Loops
Repeat code while a condition is True.
count = 0
while count < 5:
print(count)
count += 1Break and Continue
Control loop execution with break (exit loop) and continue (skip to next iteration).
for num in range(10):
if num == 3:
continue # Skip 3
if num == 7:
break # Stop at 7
print(num)Cornerstone Project — Weekly Task Prioritizer
Build a simple task prioritizer that helps you decide what to work on each day. You'll use if statements to check urgency and importance, loops to process multiple tasks, and create a practical tool you can actually use for your daily work planning.
Step 1 — Define Your Tasks
Start with a list of tasks. Each task has a name, urgency (1-5), and importance (1-5).
tasks = [
{"name": "Reply to client email", "urgency": 5, "importance": 4},
{"name": "Update project documentation", "urgency": 2, "importance": 3},
{"name": "Fix critical bug", "urgency": 5, "importance": 5},
{"name": "Team meeting prep", "urgency": 3, "importance": 3},
{"name": "Learn new Python feature", "urgency": 1, "importance": 2},
]Step 2 — Calculate Priority Score
Create a simple formula: tasks that are both urgent AND important get the highest priority.
# Add priority score to each task
for task in tasks:
# Priority = urgency + importance (max 10)
task["priority"] = task["urgency"] + task["importance"]
# Check what we have
for task in tasks:
print(f"{task['name']}: Priority {task['priority']}")Step 3 — Categorize Tasks
Use if/elif/else to assign each task to a category: Critical, High, Medium, or Low priority.
for task in tasks:
priority = task["priority"]
if priority >= 9:
task["category"] = "🔴 Critical"
elif priority >= 7:
task["category"] = "🟠 High"
elif priority >= 5:
task["category"] = "🟡 Medium"
else:
task["category"] = "🟢 Low"Step 4 — Sort and Display Your Priority List
Sort tasks by priority (highest first) and show them in a clean format.
# Sort tasks by priority (highest first)
sorted_tasks = sorted(tasks, key=lambda t: t["priority"], reverse=True)
print("
📋 Your Priority Task List")
print("=" * 50)
for i, task in enumerate(sorted_tasks, 1):
print(f"{i}. {task['category']} {task['name']}")
print(f" Priority: {task['priority']}/10")
print()Step 5 — Create Your Daily Focus List
Use a loop with break to select only the top 3 critical/high priority tasks for today.
print("
⭐ Today's Focus (Top 3 Tasks)")
print("=" * 50)
focus_count = 0
for task in sorted_tasks:
# Only include Critical and High priority
if "Critical" in task["category"] or "High" in task["category"]:
focus_count += 1
print(f"{focus_count}. {task['name']}")
# Stop after 3 tasks
if focus_count >= 3:
break
if focus_count == 0:
print("Great! No urgent tasks today. Focus on learning or planning.")Step 6 — Add a Quick Win Finder
Find tasks that are important but not urgent - perfect for when you have extra time.
print("
💡 Quick Wins (When You Have Extra Time)")
print("=" * 50)
for task in tasks:
# Important but not urgent (importance >= 3, urgency < 3)
if task["importance"] >= 3 and task["urgency"] < 3:
print(f"• {task['name']}")How This Helps Your Work
- Clear priorities - No more wondering what to work on first
- Focused days - Top 3 tasks keep you from feeling overwhelmed
- Flexible - Easy to add your own tasks each morning
- Reusable - Copy this code and adjust the tasks daily
Practice Exercise
Extend the task prioritizer by adding a "deadline" field (days until due) and adjust the priority calculation to include it.
# Try adding this to your tasks:
tasks = [
{"name": "Submit report", "urgency": 4, "importance": 5, "deadline": 1},
{"name": "Review code", "urgency": 3, "importance": 4, "deadline": 3},
]
# Hint: Increase priority if deadline is 1-2 days
for task in tasks:
priority = task["urgency"] + task["importance"]
# Your code here: add bonus points for urgent deadlines
if task["deadline"] <= 2:
priority += 2 # Boost priority for urgent deadlines
task["priority"] = priority