Python Basics - 02. Control Flow

This notebook covers conditional statements and loops. These control flow structures allow your program to make decisions and repeat tasks, which are fundamental to developing complex logic.

Download Notebook

Download this notebook

1. Conditional Statements (If, Elif, Else)

An if statement executes a block of code only if its condition is true. The elif (short for ‘else if’) can be used to check multiple conditions, and else catches anything that didn’t match the preceding conditions.

Note: Python uses indentation (typically 4 spaces) to define code blocks, unlike curly braces {} in C++ or Java.

score = 85
print(f"Your score is {score}.")

if score >= 90:
    print("Grade: Excellent (A)")
elif score >= 80:
    print("Grade: Good (B)")
elif score >= 60:
    print("Grade: Pass (C)")
else:
    print("Grade: Fail (F)")
Your score is 85.
Grade: Good (B)

2. For Loops

The for loop in Python is used to iterate over a sequence (such as a list, string, or a range object).

# Iterating over a sequence of numbers using range()
print("Counting from 0 to 4:")
for i in range(5):
    print(i, end=" ")  # Use end=" " to print on the same line
print("\n")

# Iterating over elements in a list
fruits = ["apple", "banana", "cherry"]
print("Items in the fruit list:")
for fruit in fruits:
    print(f"- {fruit}")
Counting from 0 to 4:
0 1 2 3 4 

Items in the fruit list:
- apple
- banana
- cherry

3. While Loops

A while loop continues to execute as long as its condition remains true. It’s important to update the variables within the loop so it eventually terminates, avoiding an infinite loop.

count = 1
print("Starting a while loop...")
while count <= 3:
    print(f"Count is currently {count}")
    count += 1  # Equivalent to: count = count + 1
print("Done!")
Starting a while loop...
Count is currently 1
Count is currently 2
Count is currently 3
Done!

4. Break and Continue

  • break: Immediately exits the nearest enclosing loop.

  • continue: Skips the rest of the code inside the loop for the current iteration, and moves to the next iteration.

print("\n--- Break Example ---")
for i in range(1, 10):
    if i == 5:
        print("Breaking out at i = 5")
        break
    print(i, end=" ")

print("\n\n--- Continue Example ---")
for i in range(1, 6):
    if i == 3:
        print("\nSkipping i = 3")
        continue
    print(i, end=" ")
--- Break Example ---
1 2 3 4 Breaking out at i = 5


--- Continue Example ---
1 2 
Skipping i = 3
4 5 

5. Structural Pattern Matching and Loop else

match / case (Python 3.10+)

Pattern matching lets you branch cleanly based on shape and value.

Loop else

A loop else block runs only when the loop ends normally (not via break). This is useful for search logic where you want to report “not found” cleanly.

# match/case example (Python 3.10+)
# Pattern matching is often cleaner than long if/elif chains.
def http_status_message(status_code):
    match status_code:
        case 200:
            return "OK"
        case 401 | 403:
            # Multiple literals can be grouped with |.
            return "Unauthorized or Forbidden"
        case 404:
            return "Not Found"
        case _:
            # _ is the wildcard (default branch).
            return "Unknown Status"

print(http_status_message(200))
print(http_status_message(403))
print(http_status_message(418))

# loop-else example
# else runs only if the loop finishes WITHOUT hitting break.
target = 17
numbers = [2, 5, 9, 17, 23]

for n in numbers:
    if n == target:
        print(f"Found target: {target}")
        break
else:
    print("Target not found")
OK
Unauthorized or Forbidden
Unknown Status
Found target: 17