Control Flow and Program Logic
From the Cs curriculum
Control Flow and Program Logic
TL;DR
Control flow determines the order your program's instructions are executed, enabling decisions and repetitions. It's how programs react to different situations and handle lists of items efficiently. Mastering control flow lets you write dynamic, intelligent programs instead of just simple, linear instruction sets.
1. The Mental Model
Think of your program as a recipe. Control flow lets you add "if this happens, then do that" steps or "repeat this step until the cake is done" instructions, moving beyond a simple, straight-through list of actions.
2. The Core Material
Programs aren't always a simple, straight line of instructions from top to bottom. Control flow is about changing that default order. It allows your program to make decisions, repeat actions, and jump around parts of your code. This is fundamental to creating any useful, interactive, or intelligent software.
Conditionals: Making Decisions (if, elif, else)
Conditionals allow your program to execute different blocks of code based on whether a condition is true or false.
age = 18
if age >= 18:
print("You are an adult.")
print("You can vote.")
elif age >= 13: # 'elif' means 'else if'
print("You are a teenager.")
else: # 'else' catches everything not covered by 'if' or 'elif'
print("You are a child.")
# Output for age = 18:
# You are an adult.
# You can vote.
- An
ifstatement checks its condition first. IfTrue, its block runs. elifstatements are checked only if the precedingiforelifconditions wereFalse.- The
elseblock runs only if all precedingifandelifconditions wereFalse.
Loops: Repeating Actions (for, while)
Loops let you execute a block of code multiple times.
for loops: Iterating over sequences
for loops are great when you know (or can easily determine) how many times you need to repeat, often for each item in a list or sequence.
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")
# Using range() for a fixed number of repetitions
for i in range(3): # range(3) gives numbers 0, 1, 2
print(f"Iteration {i}")
# Output:
# I like apple.
# I like banana.
# I like cherry.
# Iteration 0
# Iteration 1
# Iteration 2
while loops: Repeating until a condition is met
while loops keep executing as long as their condition remains True. You need to ensure the condition eventually becomes False to avoid an infinite loop.
count = 0
while count < 3:
print(f"Count is {count}")
count = count + 1 # This changes 'count', eventually making the condition False
# Output:
# Count is 0
# Count is 1
# Count is 2
Flow Control Statements (break, continue)
These statements let you fine-tune how loops behave.
break: Immediately exits the current loop.continue: Skips the rest of the current iteration and jumps to the next iteration of the loop.
for i in range(5):
if i == 2:
continue # Skips printing '2', goes to next iteration
if i == 4:
break # Exits loop completely when i is 4
print(i)
# Output:
# 0
# 1
# 3
Here's a diagram illustrating the decision-making process within a conditional block:
graph TD
A["Start Program"] --> B{"Is condition 1 True?"};
B -- "Yes" --> C["Execute Block 1"];
B -- "No" --> D{"Is condition 2 True?"};
D -- "Yes" --> E["Execute Block 2"];
D -- "No" --> F["Execute Block 3 (Else)"];
C --> G["Continue Program"];
E --> G;
F --> G;
3. Worked Example
Let's say you're building a simple program that checks a user's login credentials and grants access to a menu.
correct_username = "admin"
correct_password = "password123"
max_attempts = 3
attempts = 0
while attempts < max_attempts:
print(f"
Login Attempt {attempts + 1} of {max_attempts}")
username = input("Enter username: ")
password = input("Enter password: ")
if username == correct_username and password == correct_password:
print("Login successful! Welcome to the main menu.")
# Imagine actual menu display logic here
break # Exit the loop because login was successful
elif username == correct_username and password != correct_password:
print("Incorrect password.")
else:
print("Incorrect username.")
attempts = attempts + 1 # Increment attempts only if login failed
if attempts == max_attempts:
print("
Maximum login attempts reached. Account locked.")
Explanation:
1. We set up correct credentials and a limit for login attempts.
2. A while loop runs as long as attempts is less than max_attempts.
3. Inside the loop, it asks for input.
4. An if/elif/else structure checks the input:
- If both username and password are correct (username == correct_username and password == correct_password), it prints success and breaks out of the while loop.
- If only the password is wrong, it gives a specific message.
- Otherwise (any other incorrect combination, typically meaning incorrect username), it gives a general "incorrect username" message.
5. If the login failed, attempts is incremented.
6. After the loop, it checks if attempts hit max_attempts. If so, it means the loop finished without a break (i.e., login failed too many times), and the account is locked.
4. Key Takeaways
- Conditionals (
if,elif,else) empower your program to make decisions based on conditions. forloops are excellent for iterating through sequences like lists or a known number of times.whileloops repeat actions as long as a condition is true, making them suitable for indefinite repetitions.breaklets you exit a loop immediately, useful for early termination.continueskips the rest of the current loop cycle and moves to the next.- Combining these control flow tools allows for complex and dynamic program behavior.
Common Mistakes to Avoid:
- Infinite while loops: Forget to update the condition variable inside a while loop, causing it to run forever.
- Incorrect indentation: Python uses indentation to define code blocks (like those for if or loops); incorrect indentation leads to IndentationError or logic bugs.
- Off-by-one errors in range() or loop conditions: Forgetting that range(N) generates numbers from 0 up to N-1.
- Misunderstanding elif and else: elif and else blocks are only considered if all preceding conditions were false.
5. Now Try It
Write a Python program that asks the user for a number. Then, use a for loop to print all even numbers from 1 up to (and including) that user-provided number. If the user enters a non-positive number (0 or less), print an error message instead.
Success looks like: If the user enters 10, your program should print 2, 4, 6, 8, 10 each on a new line. If they enter -5, it should print "Please enter a positive number."
Frequently asked about Control Flow and Program Logic
More from Cs
Get the full Cs curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account