Control Structures
Implementing conditionals and loops for flow control
Control Structures in Python
Master Python control structures with free flashcards and spaced repetition practice. This lesson covers conditional statements (if/elif/else), loops (for/while), and flow control mechanisms (break/continue/pass)โessential concepts for writing dynamic, decision-making programs.
Welcome to Control Structures! ๐ป
Control structures are the backbone of programming logic. They allow your programs to make decisions, repeat actions, and respond dynamically to different conditions. Without control structures, your code would execute linearly from top to bottom with no ability to adapt. Think of them as the traffic signals and road signs that direct the flow of your program's execution.
Control structures are programming constructs that determine the order in which code statements execute. They give your programs the power to:
- Make decisions based on conditions
- Repeat operations efficiently
- Skip or alter normal execution flow
- Handle multiple scenarios with branching logic
Core Concepts ๐ฏ
1. Conditional Statements: if, elif, else
Conditional statements allow your program to execute different code blocks based on whether conditions are true or false. Python uses if, elif (else if), and else keywords.
Basic if statement:
age = 18
if age >= 18:
print("You can vote!")
if-else statement:
temperature = 25
if temperature > 30:
print("It's hot outside")
else:
print("Weather is pleasant")
if-elif-else chain:
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"Your grade is: {grade}")
๐ก Tip: Python evaluates conditions from top to bottom and stops at the first true condition. Order matters!
๐ง Mnemonic: "If Everything Looks Iffy, Fall back" - If, ElIf, Fallback (else)
Comparison Operators:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 5 |
> | Greater than | x > 5 |
< | Less than | x < 5 |
>= | Greater than or equal | x >= 5 |
<= | Less than or equal | x <= 5 |
Logical Operators:
| Operator | Purpose | Example |
|---|---|---|
and | Both conditions must be true | age >= 18 and has_license |
or | At least one condition must be true | is_weekend or is_holiday |
not | Reverses the condition | not is_raining |
๐ค Did you know? Python's elif is unique! Many languages use "else if" (two words), but Python combines them for cleaner code.
2. For Loops: Iterating Over Sequences
For loops iterate over sequences (lists, strings, ranges, etc.), executing a code block for each element.
Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Using range() function:
# range(stop) - generates numbers 0 to stop-1
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# range(start, stop) - generates numbers from start to stop-1
for i in range(2, 6):
print(i) # Prints 2, 3, 4, 5
# range(start, stop, step) - with custom increment
for i in range(0, 10, 2):
print(i) # Prints 0, 2, 4, 6, 8
Iterating over strings:
word = "Python"
for letter in word:
print(letter)
enumerate() for index and value:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# Output:
# 0: red
# 1: green
# 2: blue
๐ Real-world analogy: A for loop is like a factory assembly line. Each item (element) passes through the same processing station (code block) one at a time.
3. While Loops: Condition-Based Iteration
While loops continue executing as long as a condition remains true. They're perfect when you don't know in advance how many iterations you need.
Basic while loop:
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
User input validation:
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
Infinite loop with break:
while True:
user_input = input("Type 'quit' to exit: ")
if user_input == "quit":
break
print(f"You typed: {user_input}")
โ ๏ธ Warning: Always ensure your while loop has a way to become false, or you'll create an infinite loop!
4. Flow Control: break, continue, pass
These keywords modify the normal flow of loops:
break - Immediately exits the loop entirely:
for number in range(1, 100):
if number == 10:
break
print(number)
# Prints 1-9, then stops
continue - Skips the rest of the current iteration and moves to the next:
for number in range(1, 6):
if number == 3:
continue
print(number)
# Prints 1, 2, 4, 5 (skips 3)
pass - Does nothing; acts as a placeholder:
for item in items:
if item == "skip":
pass # TODO: implement later
else:
process(item)
๐ง Mnemonic: "Break Completely, Continue Cycling, Pass Patiently"
FLOW CONTROL VISUALIZATION
Normal Loop:
โโโ iteration 1 โโโ
โ iteration 2 โ
โ iteration 3 โ
โโโ iteration 4 โโโ
With break:
โโโ iteration 1
โ iteration 2
โโโ condition met โ EXIT โก
(iterations 3, 4 skipped)
With continue:
โโโ iteration 1 โโโ
โ condition met โ SKIP โท
โ iteration 3 โ
โโโ iteration 4 โโโ
5. Nested Control Structures
You can place control structures inside other control structures for complex logic:
Nested loops:
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print() # New line after inner loop
# Output:
# (1, 1) (1, 2) (1, 3)
# (2, 1) (2, 2) (2, 3)
# (3, 1) (3, 2) (3, 3)
Nested conditionals:
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("Get a license first")
else:
print("Too young to drive")
๐ก Tip: Deeply nested structures (3+ levels) can be hard to read. Consider breaking them into functions.
Detailed Examples with Explanations ๐
Example 1: Number Guessing Game ๐ฒ
import random
secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3
print("Guess the number between 1 and 10!")
while attempts < max_attempts:
guess = int(input("Enter your guess: "))
attempts += 1
if guess == secret_number:
print(f"Congratulations! You won in {attempts} attempts!")
break
elif guess < secret_number:
print("Too low!")
else:
print("Too high!")
remaining = max_attempts - attempts
if remaining > 0:
print(f"Attempts remaining: {remaining}")
else:
# This else belongs to the while loop!
print(f"Game over! The number was {secret_number}")
Explanation:
- Uses a
whileloop with a counter to limit attempts - Nested
if-elif-elseprovides feedback breakexits early on correct guess- The
elseclause on the loop executes only if the loop completes normally (withoutbreak)
๐ง Try this: Modify the code to give hints like "Very close!" when the guess is within 1 of the answer.
Example 2: Processing Student Grades ๐
students = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 67},
{"name": "Charlie", "score": 82},
{"name": "Diana", "score": 44},
{"name": "Eve", "score": 91}
]
passed = []
failed = []
for student in students:
name = student["name"]
score = student["score"]
if score >= 60:
passed.append(name)
if score >= 90:
print(f"๐ {name}: Excellent ({score})")
elif score >= 80:
print(f"โญ {name}: Very Good ({score})")
else:
print(f"โ {name}: Pass ({score})")
else:
failed.append(name)
print(f"โ {name}: Fail ({score})")
print(f"\nPassed: {len(passed)} students")
print(f"Failed: {len(failed)} students")
Explanation:
- Iterates over a list of dictionaries using a
forloop - Multiple conditional levels categorize performance
- Lists accumulate results for summary statistics
- Dictionary access retrieves student data
Example 3: Multiplication Table Generator ๐งฎ
def print_multiplication_table(max_number=10):
# Print header
print(" ", end="")
for i in range(1, max_number + 1):
print(f"{i:4}", end="")
print("\n" + "-" * (4 + max_number * 4))
# Print rows
for i in range(1, max_number + 1):
print(f"{i:3} |", end="")
for j in range(1, max_number + 1):
product = i * j
print(f"{product:4}", end="")
print() # New line after each row
print_multiplication_table(10)
Explanation:
- Nested
forloops create a 2D grid structure - Outer loop handles rows (first number)
- Inner loop handles columns (second number)
- String formatting (
{:4}) aligns output in columns end=""prevents automatic newlines
๐ Real-world use: This pattern appears in image processing (iterating over pixels), game boards, spreadsheets, and matrix operations.
Example 4: Prime Number Finder ๐ข
def find_primes(limit):
primes = []
for number in range(2, limit + 1):
is_prime = True
# Check if number is divisible by any number from 2 to sqrt(number)
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
is_prime = False
break # No need to check further
if is_prime:
primes.append(number)
return primes
primes_up_to_50 = find_primes(50)
print(f"Primes up to 50: {primes_up_to_50}")
print(f"Found {len(primes_up_to_50)} prime numbers")
Explanation:
- Outer loop iterates through candidate numbers
- Flag variable (
is_prime) tracks prime status - Inner loop tests divisibility
breakoptimizes by stopping once a divisor is found- Mathematical optimization: only checks up to square root
๐ก Tip: The break statement here provides significant performance improvement for large numbers!
Common Mistakes โ ๏ธ
1. Using Assignment (=) Instead of Comparison (==)
โ Wrong:
if x = 5: # SyntaxError!
print("x is 5")
โ Right:
if x == 5:
print("x is 5")
Why it matters: A single = is assignment; == is comparison. This is a syntax error in Python (thankfully!), but in some languages it assigns and causes subtle bugs.
2. Forgetting the Colon (:)
โ Wrong:
if age >= 18 # Missing colon
print("Adult")
โ Right:
if age >= 18:
print("Adult")
Remember: Every control structure header in Python ends with a colon!
3. Incorrect Indentation
โ Wrong:
for i in range(5):
print(i) # IndentationError!
โ Right:
for i in range(5):
print(i) # Indented 4 spaces
Python rule: Code blocks are defined by indentation (typically 4 spaces). All statements at the same level must have identical indentation.
4. Infinite Loops with While
โ Wrong:
count = 0
while count < 5:
print(count)
# Forgot to increment! Loops forever
โ Right:
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter
5. Off-by-One Errors with range()
โ Wrong (if you want 1-10):
for i in range(1, 10): # Goes 1-9
print(i)
โ Right:
for i in range(1, 11): # Goes 1-10
print(i)
๐ง Remember: range(start, stop) goes up to BUT NOT INCLUDING stop.
6. Modifying a List While Iterating Over It
โ Dangerous:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Can cause skipped elements!
โ Safe approach:
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0] # List comprehension
# Or create a new list
filtered = []
for num in numbers:
if num % 2 != 0:
filtered.append(num)
Key Takeaways ๐ฏ
โ
Conditional statements (if/elif/else) enable decision-making based on conditions
โ For loops iterate over sequences with a known or finite set of items
โ While loops continue based on conditions, perfect for unknown iteration counts
โ break exits a loop immediately; continue skips to the next iteration
โ pass is a null operation placeholder for incomplete code
โ Indentation is mandatory and defines code blocks in Python
โ range() generates sequences of numbers; remember it excludes the stop value
โ Nested structures allow complex logic but should be kept readable
โ Always ensure while loops can terminate to avoid infinite loops
โ
Use comparison operators correctly: == for equality, = for assignment
๐ Quick Reference Card
| Structure | Syntax | Use Case |
|---|---|---|
| if statement | if condition: | Single condition check |
| if-else | if condition: | Two alternatives |
| if-elif-else | if cond1: | Multiple conditions |
| for loop | for item in sequence: | Known iterations |
| while loop | while condition: | Condition-based iteration |
| break | break | Exit loop immediately |
| continue | continue | Skip to next iteration |
| pass | pass | Placeholder (do nothing) |
| range() | range(start, stop, step) | Generate number sequences |
| enumerate() | enumerate(sequence) | Get index and value |
Comparison Operators
== != > < >= <=
Logical Operators
and or not
Remember: IEIF
If ElIf else-Fallback๐ Further Study
- Python Official Documentation - Control Flow: https://docs.python.org/3/tutorial/controlflow.html
- Real Python - Conditional Statements: https://realpython.com/python-conditional-statements/
- Real Python - Python for Loops: https://realpython.com/python-for-loop/