Control Flow

Control flow allows your program to make decisions and repeat blocks of code. In Python, control flow is defined by indentation.

1. If-Else Conditionals

age = 18

    if age >= 21:
        print("Welcome to the club")
    elif age >= 18:
        print("Welcome to the cafe")
    else:
        print("Access Denied")

2. While Loops

Repeats a block of code as long as a condition is True.

count = 0
    while count < 5:
        print(f"Count is: {count}")
        count += 1

3. For Loops

Used for iterating over a sequence (list, tuple, string) or a range.

# Iterating over a range
    for i in range(5):
        print(i) # 0 to 4

    # Iterating over a list
    fruits = ["Apple", "Banana", "Cherry"]
    for fruit in fruits:
        print(fruit)

4. Break & Continue

  • break: Stops the loop entirely.
  • continue: Skips the current iteration and moves to the next.
for n in range(10):
        if n == 5:
            break # stops at 5
        if n % 2 == 0:
            continue # skips evens
        print(n)
Syntactic Sugar: Python also has a unique for...else construction where the else block runs if the loop finished normally (without a break).