Lesson 4
Mastering Python: Conditional Looping, Break, and Continue
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:

Python
1temperature = 15 2if temperature > 20: 3 print("Wear light clothes.") # This will print if temperature is over 20. 4else: 5 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":

Python
1if temperature > 30: 2 print("It's hot outside!") # Prints if temperature is over 30. 3elif temperature > 20: 4 print("The weather is nice.") # Prints if temperature is between 21 and 30. 5else: 6 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:

Python
1numbers = [1, 3, 7, 9, 12, 15] 2 3for number in numbers: 4 if number % 2 == 0: 5 print("The first even number is:", number) # Prints the first even number. 6 break # Stops the loop after printing the first even number. 7 print("Number:", number) 8# Prints: 9# Number: 1 10# Number: 3 11# Number: 7 12# Number: 9 13# The first even number is: 12
The 'continue' Statement

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

Python
1for i in range(6): 2 if i == 3: 3 continue # Skips the print command for '3'. 4 print(i) # Prints the numbers 0 to 5 except 3. 5# Prints: 6# 0 7# 1 8# 2 9# 4 10# 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":

Python
1names = ["Alice", "Bob", "Charlie", "David"] 2 3for name in names: 4 if name == "Charlie": 5 print("Found Charlie!") # Prints when 'Charlie' is found. 6 break # Stops the loop after finding Charlie.
Lesson Summary and Practice

Well done! You are now more familiar with Python's if statement, break and continue statements, and their applications with loops. It's time to refine your learning with the upcoming practice exercises. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.