Topic Overview

Welcome! Today, we're exploring Python's special instructions: Conditional Looping, along with the break and continue statements. As we know, loops enable code execution multiple times. Conditional looping, enhanced with break and continue, bolsters loop control, leading to flexible, efficient code. Grab your explorer hat, and let's get started!

The 'if' Statement

Python's if statement sets condition-based actions for our code. Consider this simple example where the if statement decides which message to print based on the value of temperature:

temperature = 15
if temperature > 20:
    print("Wear light clothes.") # This will print if temperature is over 20.
else:
    print("Bring a jacket.") # This will print otherwise.

We can also evaluate multiple conditions using elif. In other words, "If the previous condition isn't true, then check this one":

if temperature > 30:
    print("It's hot outside!") # Prints if temperature is over 30.
elif temperature > 20:
    print("The weather is nice.") # Prints if temperature is between 21 and 30.
else:
    print("It might be cold outside.") # Prints if temperature is 20 or below.
The 'break' Statement

We use the break statement whenever we want to exit a loop prematurely once a condition is met:

numbers = [1, 3, 7, 9, 12, 15]

for number in numbers:
    if number % 2 == 0:
        print("The first even number is:", number) # Prints the first even number.
        break # Stops the loop after printing the first even number.
    print("Number:", number)
# Prints:
# Number: 1
# Number: 3
# Number: 7
# Number: 9
# The first even number is: 12
The 'continue' Statement

The continue statement bypasses the rest of the loop code for the current iteration only:

for i in range(6):
    if i == 3:
        continue # Skips the print command for '3'.
    print(i) # Prints the numbers 0 to 5 except 3.
# Prints:
# 0
# 1
# 2
# 4
# 5
Use-case with a For Loop

By combining the tools we've learned so far, we can write more flexible loops. Here's a snippet where we conclude the loop once we find "Charlie":

names = ["Alice", "Bob", "Charlie", "David"]

for name in names:
    if name == "Charlie":
        print("Found Charlie!") # Prints when 'Charlie' is found.
        break # Stops the loop after finding Charlie.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal