DSPython Logo DSPython

Control Statements

Control the flow of your loops with break, continue, and pass.

Python Basics Beginner 30 min

🎮 Control Flow in Loops

Imagine you are listening to a playlist of 100 songs on Spotify.

1. If you don't like the current song, you press "Next" to skip just that song (this is continue).
2. If you reach your destination and want to stop the music entirely, you press "Stop" (this is break).
3. If you want to create a playlist folder but haven't decided on the name yet, you leave it empty for now (this is pass).

Loops (for and while) are powerful, but sometimes we need to alter their standard behavior. We call these Loop Control Statements. They allow you to handle edge cases, search for data efficiently, and avoid processing unnecessary information.

🛑 Topic 1: The break Statement

The break statement is the "Emergency Stop" button. It is used to exit a loop completely, immediately.

Regardless of whether the loop was supposed to run 100 more times, hitting a break statement kills the loop instantly. The program control jumps to the very next line of code outside the loop.

📝 When to use break?

  • Search Operations: "I found what I was looking for, no need to check the rest of the items."
  • User Input: "The user typed 'quit', so stop the program."
  • Safety Limits: "The temperature exceeded 100°C, stop the machine immediately."

💻 Example: Search for a Number

# We want to find if 50 is in the list.
numbers = [10, 20, 50, 60, 70]

for num in numbers:
print(f"Checking {num}...")
if num == 50:
print("Found it! Stopping search.")
break  # Loop ends here. 60 and 70 are NEVER checked.

# Output:
# Checking 10...
# Checking 20...
# Checking 50...
# Found it! Stopping search.

⚠️ Nested Loops Warning:

If you have a loop inside another loop (nested loop), break will only exit the inner loop. The outer loop will continue running.

⏭️ Topic 2: The continue Statement

The continue statement tells Python: "Skip the rest of the code for this specific time, and go back to the top to start the next round."

It does not terminate the loop. It just shortcuts the current iteration.

[Image of flowchart showing continue statement logic]

📝 Real-World Use Case: Data Cleaning

In Data Science (DSPython!), you often have "dirty" data. For example, missing values or negative numbers where positive ones are expected. You can use continue to skip the bad data points and process only the good ones.

💻 Example: Processing Prices

# We want to add tax to prices, but skip free items (0)
prices = [100, 0, 200, 0, 50]

for price in prices:
if price == 0:
print("Skipping free item...")
continue  # Jump back to start of loop
# This calculation only happens if price is NOT 0 total = price * 1.18
print(f"Price with tax: {total}")

# Notice how "Price with tax" is never printed for 0

⚪ Topic 3: The pass Statement

The pass statement is unique to Python. In languages like C or Java, you can just leave empty curly braces {} if you don't want to do anything. In Python, because we use indentation, we cannot leave a block completely empty.

The pass statement is literally a "Do Nothing" command. It is strictly used to satisfy syntax requirements while you are still planning your code (often called "Stubbing").

💻 Example: Planning a Project

# I am building a game, but haven't written the logic yet

def player_attack():
pass # TODO: Add damage calculation

def player_defend():
pass # TODO: Add armor logic

class EnemyBoss:
pass # Will design boss later

# Without 'pass', all of the above would cause errors!

🦄 Topic 4: The Loop else Block

Wait, else in a loop? Yes! This is a special Python feature that confuses many beginners. You can put an else block after a for or while loop.

The logic is: The else block executes ONLY if the loop finishes normally (i.e., it was NOT stopped by a break statement).

🧠 Easy Way to Remember:

  • Break hit? -> No Else.
  • No Break hit? -> Yes Else.

💻 Example: Prime Number Checker

# Check if 7 is prime
num = 7

for i in range(2, num):
if num % i == 0:
print("Not Prime")
break # We found a divisor, stop checking
else:
# This runs only if the loop completed without breaking print("It is Prime!")

📚 Loop Control Cheat Sheet

Statement Analogy Action
break Emergency Brake Kills the loop entirely
continue Skip Song Skips current turn, goes to next
pass Empty Sticky Note Does absolutely nothing

🎉 Congratulations!

You now control the flow of your programs like a pro.