Learn Python · 3/15

Control Flow: Making Decisions

8 min read

Hey there! Welcome to the world of Python's control flow. So far, your code has been running like a train on a single track—straight from top to bottom. But what if you want your program to be smarter? What if you want it to make decisions, react to different situations, or repeat tasks? That's where control flow comes in. It gives your program a brain 🧠.

By the end of this guide, you'll be able to tell your Python programs how to think, not just what to do. Let's get started!


1. Conditional Statements: if, elif, and else 🧐

The Problem

Imagine you're writing a program for a movie theater. You need to check if a person is old enough to see an R-rated movie. Your program needs to make a decision: if the person's age is 18 or over, let them in. If not, tell them they're too young. A simple top-to-bottom script can't handle this choice.

The Solution: if, elif, and else

These statements let your program execute certain pieces of code only when a specific condition is true.

if: The Basic Decision

The if statement is the simplest form of decision-making. It checks a condition, and if that condition is True, it runs a block of code.

Syntax & Example:

python
age = 20

if age >= 18:
  print("✅ You are old enough to watch this movie.")

print("This line runs no matter what.")

Explanation:
Because age (which is 20) is greater than or equal to 18, the condition is True, and the message is printed. The code inside the if statement is indented (usually with 4 spaces), which is how Python knows it belongs to the if block.

else: The "Otherwise" Plan

The else statement gives you an alternative block of code to run if the if condition turns out to be False.

Syntax & Example:

python
age = 15

if age >= 18:
  print("✅ You are old enough to watch this movie.")
else:
  print("🚫 Sorry, you must be 18 or older to watch this movie.")

Explanation:
Here, age is 15. The if condition (15 >= 18) is False, so Python skips the if block and jumps straight to the else block to execute that code instead.

elif: Handling Multiple "Else If" Conditions

What if you have more than two possibilities? For example, a grading system (A, B, C, D, F). This is where elif (short for "else if") comes in. It lets you check multiple conditions in a chain.

Syntax & Example:

python
score = 85

if score >= 90:
  print("Grade: A")
elif score >= 80:
  print("Grade: B")
elif score >= 70:
  print("Grade: C")
else:
  print("Grade: F")

# Output: Grade: B

Explanation:
Python checks the conditions one by one from top to bottom:

  1. Is score >= 90? (85 >= 90 is False).
  2. OK, let's check the next one. Is score >= 80? (85 >= 80 is True).
  3. Aha! This one is true. Python prints "Grade: B" and then skips the rest of the elif and else blocks completely.

✨ Fun Fact: Python's use of indentation to define code blocks is a core feature of the language. In many other languages, programmers use curly braces {}. This design choice makes Python code very readable and less cluttered.


2. The 'for' Loop: Iterating Over Sequences 🔁

The Problem

Let's say you have a list of guest names, and you want to print a personalized welcome message for each one. You could write print("Welcome, Alice!"), print("Welcome, Bob!"), etc. But what if you have 1,000 guests? That would be a nightmare! You need a way to do the same action for every item in a sequence.

The Solution: for Loops

A for loop is used to iterate over a sequence (like a list, tuple, dictionary, or string) and execute a block of code for each item in that sequence.

Looping Through a List

This is the most common use of a for loop.

Syntax & Example:

python
guests = ["Alice", "Bob", "Charlie"]

for guest in guests:
  print(f"🎉 Welcome to the party, {guest}!")

Explanation:

  1. The loop starts with the first item in guests, "Alice".
  2. It assigns "Alice" to the variable guest.
  3. It runs the code inside the loop: print("🎉 Welcome to the party, Alice!").
  4. It then moves to the next item, "Bob", assigns it to guest, and runs the code again.
  5. This continues until every item in the list has been processed.

The range() Function: Looping a Specific Number of Times

Sometimes you don't have a list to loop over, but you want to repeat an action a certain number of times. The range() function is perfect for this.

Syntax & Example:

python
# The range(5) function generates numbers from 0 up to (but not including) 5.
for i in range(5):
  print(f"This is loop number {i}")

Output:

ada
This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

Under the Hood: A for loop works on anything in Python that is "iterable." Think of an iterable as a collection of items that can be gone through one by one, like a list of items on a conveyor belt. The for loop is the worker that picks up each item and does something with it.


3. The 'while' Loop: Condition-Based Looping ⏳

The Problem

Imagine you are writing a simple game. You want the game to keep running as long as the player has lives left. You don't know ahead of time how many turns this will take. A for loop isn't a good fit because it runs for a fixed number of times. You need a loop that continues until a condition changes.

The Solution: while Loops

A while loop repeatedly executes a block of code as long as a given condition remains True.

Syntax & Example:

python
import time
import random

player_hp = 10

while player_hp > 0:
  print(f"Player HP: {player_hp}. You are still in the fight!")
  damage = random.randint(1, 4) # Take a random amount of damage
  print(f"You took {damage} damage!")
  player_hp -= damage # Same as player_hp = player_hp - damage
  time.sleep(1) # Pause for 1 second to make it readable

print("☠️ Player HP is 0. Game Over!")

Explanation:

  1. The while loop first checks if player_hp > 0.
  2. If it's True, it runs the indented code block.
  3. After the block finishes, it goes back to the top and checks the condition again.
  4. This process repeats until player_hp is no longer greater than 0, at which point the condition becomes False, and the loop terminates.

🚨 The Danger: Infinite Loops! 😱
A common mistake is creating a while loop where the condition never becomes False. This is called an infinite loop, and it will cause your program to hang and run forever.

python
# DANGER: Infinite loop!
# The value of `x` never changes, so it will always be less than 10.
x = 5
while x < 10:
  print("This will run forever!")

Always make sure that something inside your while loop will eventually cause the condition to become False.


4. Loop Control: break, continue, and pass 🚦

The Problem

Sometimes, you need to change a loop's behavior while it's running. Maybe you've found what you were looking for and want to stop early. Or maybe you want to skip over a specific item and move to the next one. These statements give you that finer control.

break: Exiting a Loop Immediately

The break statement terminates the current loop and transfers control to the statement immediately following the loop.

Analogy: break is like finding your car in a massive parking lot. Once you find it, you stop searching and head home. You don't need to check the remaining 500 parking spots.

Example:

python
numbers = [1, 5, 9, 12, 15, 22, 30]

for num in numbers:
  print(f"Checking {num}...")
  if num > 10:
    print("Found a number greater than 10! Stopping the search.")
    break # Exit the loop now!

print("Loop finished.")

continue: Skipping to the Next Iteration

The continue statement rejects all the remaining statements in the current iteration of the loop and moves control back to the top of the loop to begin the next iteration.

Analogy: continue is like an assembly line worker who spots a defective product. They toss that one product aside (continue) and immediately get ready for the next one coming down the belt.

Example:

python
# Print only the odd numbers
for i in range(1, 11): # Numbers from 1 to 10
  if i % 2 == 0: # Check if the number is even
    continue # If it's even, skip the print statement and go to the next number
  print(i)

pass: The "Do Nothing" Statement

The pass statement does nothing. It's a null operation. So why does it exist? Sometimes, Python's syntax requires an indented block of code (e.g., after an if or in a for loop), but you haven't written the logic for it yet. pass acts as a placeholder to prevent a syntax error.

Example:

python
def process_admin_login():
  # TODO: Write the logic for admin login later.
  # For now, just let it pass without causing an error.
  pass

def process_user_login():
  print("Processing standard user login...")

process_admin_login() # This does nothing, but the program runs fine.

Funny take: pass is the programmer's way of saying, "I acknowledge this exists, but I'll deal with it later."


Extra Reading & References

For more in-depth information, check out the official Python documentation:

Challenge

You are monitoring a stream of sensor data represented by a list of integers. Your task is to write a Python script to process these readings according to specific rules.

Write a script that iterates through the sensor_readings list and performs the following actions for each reading:

  1. If a reading is 95 or higher, print the message "CRITICAL: System shutting down." and immediately terminate the loop.
  2. If a reading is between 80 and 94 (inclusive), print "Warning: High reading of [value] detected." where [value] is the sensor reading.
  3. If a reading is negative, it's considered an invalid data point. Print "Invalid reading ignored." and skip to the next reading without performing any other checks on it.
  4. For all other valid readings, print "Normal: Reading [value] OK.".

Expected result

Your script should produce the following output line-by-line, exactly as shown. Note that processing stops once the critical value is encountered.

erlang
Normal: Reading 45 OK.
Normal: Reading 62 OK.
Invalid reading ignored.
Warning: High reading of 81 detected.
Warning: High reading of 90 detected.
Normal: Reading 75 OK.
CRITICAL: System shutting down.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.