You are viewing a preview of this lesson. Sign in to start learning
Back to Python Programming

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:

OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater than or equalx >= 5
<=Less than or equalx <= 5

Logical Operators:

OperatorPurposeExample
andBoth conditions must be trueage >= 18 and has_license
orAt least one condition must be trueis_weekend or is_holiday
notReverses the conditionnot 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 while loop with a counter to limit attempts
  • Nested if-elif-else provides feedback
  • break exits early on correct guess
  • The else clause on the loop executes only if the loop completes normally (without break)

๐Ÿ”ง 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 for loop
  • 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 for loops 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
  • break optimizes 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

StructureSyntaxUse Case
if statementif condition:Single condition check
if-elseif condition:
    ...
else:
    ...
Two alternatives
if-elif-elseif cond1:
    ...
elif cond2:
    ...
else:
    ...
Multiple conditions
for loopfor item in sequence:Known iterations
while loopwhile condition:Condition-based iteration
breakbreakExit loop immediately
continuecontinueSkip to next iteration
passpassPlaceholder (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

  1. Python Official Documentation - Control Flow: https://docs.python.org/3/tutorial/controlflow.html
  2. Real Python - Conditional Statements: https://realpython.com/python-conditional-statements/
  3. Real Python - Python for Loops: https://realpython.com/python-for-loop/

Practice Questions

Test your understanding with these questions:

Q1: Write a Python function that takes a number and prints all even numbers from 0 up to (and including) that number using a for loop.
A: !AI