Back to Python

Python Control Flow

Conditional Statements

Control the flow of your program with if, elif, and else statements. Python uses indentation to define code blocks.

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

The conditions are evaluated in order, and only the first true block is executed.

For Loops

For loops iterate over sequences (lists, tuples, strings, etc.) or other iterable objects.

# Iterate through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Using range()
for i in range(5):
    print(i) # Prints 0 to 4

# With else clause
for x in range(3):
    print(x)
else:
    print("Loop completed")

While Loops

While loops execute as long as a condition remains true.

# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1

# With else clause
num = 3
while num > 0:
    print(num)
    num -= 1
else:
    print("Countdown finished!")

Control Statements

Break, continue, and pass statements modify loop behavior.

# break example
for val in "string":
    if val == "i":
        break
    print(val)

# continue example
for val in "string":
    if val == "i":
        continue
    print(val)

# pass example
for val in "string":
    if val == "i":
        pass # Does nothing
    print(val)

Match-Case (Python 3.10+)

Structural pattern matching similar to switch-case in other languages.

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

Python Control Flow Videos

Master Python conditionals, loops and control structures with these handpicked YouTube tutorials:

Python Control Flow Quiz