No history yet

Control Flow

Making Decisions with Code

Programs often need to make choices. The if-elif-else structure is Python's way of handling complex decisions. It evaluates conditions one by one until it finds one that is true. Once a true condition is found, its corresponding block of code is executed, and the rest of the structure is skipped.

score = 85

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

# Output: Grade: B

In this example, the program checks the first condition (score >= 90), which is false. It then moves to the next elif condition (score >= 80), which is true. It prints "Grade: B" and ignores the remaining conditions. If no conditions were true, the final else block would run.

Repeating Tasks with Loops

Loops are fundamental for automation. They let you execute a block of code multiple times without rewriting it. Python offers two main types of loops: for and while.

A for loop is used for iterating over a sequence (like a list, tuple, or string). A while loop repeats as long as a certain condition is true.

Here’s a for loop that iterates through a list of numbers:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num * 2)

# Output:
# 2
# 4
# 6
# 8
# 10

Now, let's look at a while loop. This type of loop is useful when you don't know in advance how many times you need to repeat. You just need a condition to stop.

count = 0
while count < 5:
    print(f"Count is: {count}")
    count += 1 # This is crucial to prevent an infinite loop

# Output:
# Count is: 0
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4

A common mistake with while loops is creating an infinite loop. This happens if the condition never becomes false. Always ensure that something inside the loop changes the state of the condition.

You can also nest loops inside one another. This is common when working with multi-dimensional data, like a grid or a matrix.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for item in row:
        print(item, end=" ")
    print() # Move to the next line after each row

# Output:
# 1 2 3 
# 4 5 6 
# 7 8 9 

Advanced Loop Control

Sometimes you need more granular control over your loops. Python provides statements to change the standard loop behaviour.

StatementDescription
breakExits the current loop immediately.
continueSkips the rest of the current iteration and moves to the next.
passDoes nothing. It acts as a placeholder.

Here is how break can be used to find an item and stop searching:

fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
    if fruit == "cherry":
        print("Found the cherry!")
        break
    print(fruit)

# Output:
# apple
# banana
# Found the cherry!

And here’s continue used to skip processing for a specific condition:

for num in range(1, 6):
    if num == 3:
        continue
    print(f"Processing number {num}")

# Output:
# Processing number 1
# Processing number 2
# Processing number 4
# Processing number 5

The pass statement is less common in finished code but is useful when you are sketching out functions or conditional logic and need a placeholder to avoid a syntax error.

def my_future_function():
    pass # I'll write the logic here later

A unique feature of Python loops is the optional else block. This block executes only if the loop completes its entire sequence without being terminated by a break statement.

for i in range(5):
    print(i)
    if i == 10: # This condition is never met
        break
else:
    print("Loop finished without a break.")

# Output:
# 0
# 1
# 2
# 3
# 4
# Loop finished without a break.

This is particularly useful when searching for an item. The else block can handle the case where the item was not found.

Ready to test your knowledge?

Quiz Questions 1/6

What is the output of the following Python code snippet?

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")
Quiz Questions 2/6

Which statement correctly describes the difference between break and continue inside a loop?

Mastering control flow is a key step in writing programs that can perform complex, dynamic tasks. These structures are the building blocks of application logic.