Skip to content

Python Control Flow

Control Flow allows program to make decisions, execute different code paths based on data, and handle complex logic.


It is a block of code that only runs if a specific condition is met. Think of it like a fork in the road: “If the traffic light is red, stop. Otherwise, go.”

The simplest form. If the condition evaluates to True, the code inside the block executes. If False, it is skipped.

Terminal window
if condition:
# Code to run if True (Must be indented)
Terminal window
age = 20
if age >= 18:
print("Access Granted") # Runs because 20 >= 18 is True

Handles the “No” scenario. If the condition is True, do Task A. If False, do Task B.

Terminal window
temperature = 15
if temperature > 20:
print("It's warm outside.")
else:
print("Wear a jacket.") # Runs because 15 is not > 20

> All code belonging to the if block must be indented by 4 spaces (or 1 tab).


Used when you have more than two possible outcomes. elif stands for “Else If”.

  • Python checks conditions from top to bottom.

  • As soon as one condition is True, Python runs that block and skips the rest.

Terminal window
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B") # This runs. Python stops checking here.
elif score >= 70:
print("Grade: C") # Skipped, even though 85 > 70.
else:
print("Fail")

You can put an if inside another if for hierarchical decisions.

Terminal window
num = 10
if num >= 0:
if num == 0:
print("Number is Zero")
else:
print("Positive Number")
else:
print("Negative Number")

A shorthand way to write simple if-else statements. Great for assigning variables concisely.

Syntax: value_if_true if condition else value_if_false

Terminal window
age = 20
# Professional One-Liner
status = "Adult" if age >= 18 else "Minor"
print(status)

You don’t need to write if len(list) > 0. Python allows you to check objects directly.

  • Falsy Values (Count as False): 0, 0.0, “” (Empty String), [] (Empty List), None, False.

  • Truthy Values (Count as True): Everything else.

Terminal window
my_list = []
# Pythonic Check
if not my_list:
print("List is empty") # This runs because [] is Falsy

When mixing and / or, the order of operations can get confusing. Always use parentheses () to group logic explicitly. This prevents bugs.

Terminal window
is_admin = False
is_member = True
has_paid = False
# Clear Logic: Admin gets in OR (Member who has paid) gets in.
if is_admin or (is_member and has_paid):
print("Access Granted")

The match statement is a powerful upgrade to the traditional “Switch Case” found in other languages. It performs **Structural Pattern Matching **checking not just values, but the shape of the data.

Replaces long chains of if-elif-elif.

Terminal window
status = 404
match status:
case 200:
print("Success")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown Status") # The '_' acts as the 'else' (Default)

The match statement can unpack lists and tuples instantly.

Terminal window
# A command system
command = ["move", 10, 5]
match command:
case ["start"]:
print("System Starting...")
case ["move", x, y]:
# Matches a list with exactly "move" and two numbers
print(f"Moving to X:{x}, Y:{y}")
case ["stop"]:
print("Stopping")
case _:
print("Invalid Command")
  • Pipe (|): Matches multiple options.

  • Guard (if): Adds logic inside the match.

Terminal window
num = 10
match num:
case 1 | 2 | 3:
print("Small Number (1-3)")
case x if x > 100:
print("Huge Number")
case _:
print("Regular Number")

Loops allow you to run a block of code multiple times without rewriting it. Whether you need to process 10 items or 10 million, loops make it possible.


A loop is a control structure that repeats a block of code as long as a specific condition is met.

  • For Loop: Used when you know how many times you need to repeat (e.g., “Do this for every student in the class”).

  • While Loop: Used when you don’t know how many times, but you know the stop condition (e.g., “Keep running until the battery dies”).

Before using loops, you must understand range(). It generates a sequence of numbers and is the engine behind most loops.

  • Syntax: range(start, stop, step)

  • Crucial Rule: The stop number is excluded.

Terminal window
# 1. Basic (0 to stop-1)
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
# 2. Start and Stop
print(list(range(2, 6))) # Output: [2, 3, 4, 5]
# 3. Steps (Skipping numbers)
print(list(range(0, 10, 2))) # Output: [0, 2, 4, 6, 8]

The for loop is used to iterate over a Sequence (like a List, Tuple, String, or Dictionary). It is safer than while because it automatically stops when it reaches the end of the sequence.

Syntax:

Terminal window
for item in sequence:
# Do something with item
Terminal window
# 1. List
fruits = ["Apple", "Banana"]
for fruit in fruits:
print(fruit)
# 2. String (Character by Character)
for char in "Python":
print(char)
# 3. Using Range (Counting)
for i in range(3):
print(f"Iteration {i}")

The while loop keeps running as long as the condition is True.

  • If the condition never becomes False, you create an Infinite Loop (which crashes your program).

Syntax:

Terminal window
while condition:
# Code to repeat
# Important: Update variables to eventually end the loop!

Example:

Terminal window
battery = 3
while battery > 0:
print(f"Phone is on. Battery: {battery}%")
battery -= 1 # Decrease battery (Critical Step!)
print("Phone died.")

A unique Python feature. The else block runs once when the loop finishes normally (i.e., the condition becomes False).

  • *Note: If you stop the loop abruptly using *break, the else block is SKIPPED.
Terminal window
x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop finished successfully without break.")

Sometimes you need to interrupt the standard flow of a loop.

KeywordDescriptionAnalogybreakStops the loop entirely and exits.“Emergency Stop Button”continueSkips the current iteration and moves to the next one.“Skip this song”passDoes nothing. Used as a placeholder.“I’ll do this later”

Stops the loop immediately, even if the condition is still True.

Terminal window
# Stop searching when we find "Target"
items = &#91;"Book", "Pen", "Target", "Pencil"]
for item in items:
if item == "Target":
print("Found it!")
break # Exit loop immediately
print(f"Checking {item}...")

Jumps back to the top of the loop for the next round, ignoring any code below it.

Terminal window
# Print only odd numbers
for i in range(5):
if i % 2 == 0:
continue # Skip even numbers
print(i) # This only runs for 1, 3

Loops cannot be empty. If you are structuring code but haven’t written the logic yet, use pass.

Terminal window
for x in &#91;1, 2, 3]:
pass # To be implemented later (No Error)

A loop inside another loop. This is commonly used for working with grids, matrices, or combinations.

Logic: For every one iteration of the Outer Loop, the Inner Loop runs completely.

Terminal window
colors = &#91;"Red", "Blue"]
items = &#91;"Car", "Bike"]
for color in colors: # Outer Loop
for item in items: # Inner Loop
print(color, item)
# Output:
# Red Car
# Red Bike
# Blue Car
# Blue Bike

Comprehensions allow you to create lists, dictionaries, or sets in a single, concise line. They are often faster than traditional loops.

Syntax: [expression for item in iterable if condition]

Terminal window
fruits = &#91;"apple", "banana", "cherry", "kiwi", "mango"]
# Goal: Create a list of fruits containing "a"
# Traditional Way (4 lines)
# newlist = &#91;]
# for x in fruits:
# if "a" in x:
# newlist.append(x)
# The Pro Way (1 line)
newlist = &#91;x for x in fruits if "a" in x]
print(newlist) # &#91;'apple', 'banana', 'mango']

Same logic, different brackets.

Terminal window
# Dictionary: {Name: Length}
names = &#91;"Alice", "Bob"]
lengths = {name: len(name) for name in names} # {'Alice': 5, 'Bob': 3}
# Set: Unique Squares
nums = &#91;1, 1, 2, 2]
squares = {x**2 for x in nums} # {1, 4}

Beginners often create a separate counter variable (i = 0) to track the index. Don’t do this. Use enumerate() to get both the index and value instantly.

Terminal window
names = &#91;"Alice", "Bob", "Charlie"]
# Professional Way
for index, name in enumerate(names):
print(f"User {index}: {name}")

If you need to loop through two lists at the same time, use zip().

Terminal window
names = &#91;"Alice", "Bob"]
ages = &#91;25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

Sometimes (like in game servers or chatbots), you want a loop to run forever until a user stops it.

Terminal window
while True:
command = input("Type 'exit' to stop: ")
if command == 'exit':
break
print(f"You typed: {command}")

The else block in a for loop runs only if the loop completed without hitting a break.

Terminal window
numbers = &#91;1, 3, 5, 7]
for n in numbers:
if n == 4:
print("Found 4!")
break
else:
# This runs because 'break' was never hit
print("4 was not found in the list.")

Why can you loop through a List but not an Integer? Because Lists are Iterable.

  • Iterable: An object capable of returning its members one by one.

  • Iterator: The agent that actually fetches the next item.

When you run a for loop, Python secretly does this:

  • Calls iter(object) to get an iterator.

  • Calls next(iterator) repeatedly to get items.

  • Stops when it hits a StopIteration error.

List Comprehensions [] create the entire list in memory immediately. If the list has 1 billion items, your computer crashes. Generator Expressions () produce items one by one, using almost zero memory.

Terminal window
import sys
# List Comprehension (Greedy - Allocates memory for ALL numbers)
heavy_list = &#91;x**2 for x in range(10000)]
print(sys.getsizeof(heavy_list)) # ~87,000 bytes
# Generator Expression (Lazy - Generates on demand)
light_gen = (x**2 for x in range(10000))
print(sys.getsizeof(light_gen)) # ~100 bytes (Tiny!)
  • Use Generators for large datasets or file processing.