Previous | Tutorial index | Next

Tutorial 3: Controlling the Flow – break and continue

Learning Objective

Master the break and continue statements to precisely control the execution flow of your loops, allowing for early exits and selective skipping of iterations.

1. The Philosophy of Flow Control

Imagine you are flipping through a stack of flashcards to find a specific one.

Both statements manipulate the natural flow of a loop, but they do so in fundamentally different ways. They are the "emergency eject" and the "skip button" of programming.

2. The break Statement – Exiting the Loop Early

The break statement is a hard stop. When Python encounters break inside a loop, it immediately terminates the entire loop (the innermost one if loops are nested) and jumps to the first line of code after the loop.

Syntax and Basic Example

for item in collection: if some_condition: break # Boom! The loop is over. # Code here is skipped if break runs. # Code here runs after the loop ends (whether by break or naturally).

Let's Trace the "Negative Number" Example:

numbers = [10, 20, -5, 30, 40] for num in numbers: if num < 0: print("Negative number found! Stopping.") break print(num) print("Loop has ended.")

Mental Trace:

  1. num = 10: Is 10 < 0? No. Print 10.
  2. num = 20: Is 20 < 0? No. Print 20.
  3. num = -5: Is -5 < 0? Yes! Print "Negative number found! Stopping."EXECUTE break → Instantly jump out of the loop!
  4. (Skipped) 30 and 40 are never processed.
  5. Print "Loop has ended."

Output:

10 20 Negative number found! Stopping. Loop has ended.

break in while Loops: break works exactly the same way. It is incredibly useful for scenarios where the "natural" condition isn't the only way out (like while True patterns).

while True: user_input = input("Type 'exit' to stop: ") if user_input == "exit": break print(f"You typed: {user_input}") print("Goodbye!")

3. The continue Statement – Skipping the Current Iteration

The continue statement is a soft skip. When Python encounters continue, it immediately stops executing the current iteration and jumps back to the start of the loop for the next iteration.

Let's Trace the "Skip Even Numbers" Example:

for num in range(10): # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 if num % 2 == 0: continue print(f"Odd number: {num}")

Mental Trace:

  1. num = 0: Is 0 % 2 == 0? Yes (even). Execute continue. Skip print. Jump to next iteration (num = 1).
  2. num = 1: Is 1 % 2 == 0? No. Execute print(f"Odd number: 1").
  3. num = 2: Is 2 % 2 == 0? Yes. Execute continue. Skip print.
  4. num = 3: Print "Odd number: 3". ... and so on.

Output:

Odd number: 1 Odd number: 3 Odd number: 5 Odd number: 7 Odd number: 9

4. 🚨 CRUCIAL WARNING: The continue Infinite Loop Trap in while

This is one of the most common and frustrating bugs for beginners. Because continue jumps back to the top of the loop, it skips everything below it. If you place your counter/update logic below the continue, you will create an infinite loop!

❌ DANGEROUS CODE (Infinite Loop):

x = 0 while x < 5: if x % 2 == 0: # When x is 0 (even), this is True. continue # Jumps back to 'while x < 5'. x is STILL 0! print(x) x += 1 # This line is NEVER reached because x is always 0!

Result: The program freezes because x never changes from 0.

✅ SAFE FIX #1: Update BEFORE continue:

x = 0 while x < 5: if x % 2 == 0: x += 1 # Increment FIRST, then skip the rest. continue print(x) # Only reaches here if x is odd. x += 1

Output: 1, 3

✅ SAFE FIX #2: Use if-else (Cleaner approach): Often, a well-structured if-else eliminates the need for continue entirely, which is safer.

x = 0 while x < 5: if x % 2 != 0: # Only do something if it's odd. print(x) x += 1 # The increment is outside the if, always runs.

Output: 1, 3

5. break vs continue – A Quick Decision Matrix

Feature break continue
What it does Exits the entire loop immediately. Skips the rest of the current iteration only.
Effect on the loop The loop stops completely. The loop continues with the next item/iteration.
Use case You found exactly what you were looking for. You encountered data you want to ignore.
In while loops Stops regardless of condition. Jumps to re-evaluate the condition. (Beware of skipping updates!)
Analogy Hitting "eject" on a DVD player. Hitting "next track" on a music playlist.

6. Nested Loops: Which one do they affect?

This is a critical rule: break and continue only affect the innermost loop they are directly inside.

for i in range(3): # Outer loop print(f"Outer: {i}") for j in range(5): # Inner loop if j == 2: break # This ONLY breaks the 'j' loop! print(f" Inner: {j}") print("Inner loop finished, back to outer.")

Output: You will see "Outer: 0", "Inner: 0", "Inner: 1", then the inner loop breaks. The outer loop continues to "Outer: 1", "Outer: 2". The break does NOT stop the outer loop.

7. The "Else" Clause for Loops (A Python Bonus)

Python has a unique feature: you can attach an else clause to a for or while loop. The else block runs only if the loop completes normally (i.e., it was not exited by a break).

Why use it? It makes "search failed" logic extremely elegant.

# Looking for a specific number search_for = 50 numbers = [10, 20, 30, 40] for num in numbers: if num == search_for: print(f"Found {search_for}!") break else: # This runs ONLY if break NEVER happened. print(f"{search_for} was not found in the list.")

Output: 50 was not found in the list.

8. Common Pitfalls

  1. Infinite while with continue (as covered above).

  2. Overusing break and continue: Using too many of these makes code look like "spaghetti" and is hard to read. Often, a well-written condition (while x < 10 and not found) is cleaner than a break.

  3. Unexpected break in if blocks: Remember, break only works if you are inside a loop. if statements do not isolate them.

    # SYNTAX ERROR! if x > 5: break # Error! 'break' outside loop.
  4. continue skipping necessary cleanup: If you open a file or create a network connection inside a loop, a continue might skip the closing logic (though usually handled by with blocks). Be mindful of what you skip!

📝 Quiz: Check Your Understanding

Take a moment to answer these without running the code!

Q1: How many times does the print("Hello") statement execute?

for i in range(1, 6): if i % 3 == 0: break print("Hello")

a) 1 time
b) 2 times
c) 5 times
d) Infinite loop

Answer(B) – prints for i=1 only, breaks at 3.

Q2: What is the output of this code?

x = 0 while x < 3: x += 1 if x == 2: continue print(x, end=" ")

a) 1 2 3
b) 1 3
c) 2 3
d) 1 2

Answer(B) – skips printing 2.

Q3: (True/False) Using break inside a nested loop will terminate both the inner and outer loops immediately.

AnswerFalse – only the innermost loop.

Q4: What is the final value of x after this runs?

for x in range(5): if x == 2: break print(x)

a) 2
b) 4
c) Error (x undefined)

Answer(A) – x retains the value 2 after break.

💻 In-Tutorial Coding Exercises

Open your Python IDE. Write the code for the following challenges and run them to verify!

Exercise 1 (Search & Break): Given the list temperatures = [72, 68, 75, 90, 82, 55, 60], write a for loop that prints each temperature. If the temperature exceeds 85, print "Too hot!" and immediately stop the loop (using break).

Solution
temps = [72, 68, 75, 90, 82, 55, 60] for t in temps: if t > 85: print("Too hot!") break print(t)

Exercise 2 (Filtering with continue): Write a loop that iterates over the string "Python Programming". Print only the consonants (ignore vowels: a, e, i, o, u - case-insensitive). Use continue to skip vowels.

Solution
text = "Python Programming" for ch in text: if ch.lower() in "aeiou ": continue print(ch, end="")

Exercise 3 (Safe while with continue): Write a while loop that prints the numbers from 1 to 10, but skips printing numbers that are divisible by 3. Ensure you do NOT create an infinite loop.

Solution
i = 1 while i <= 10: if i % 3 == 0: i += 1 continue print(i) i += 1

Exercise 4 (Loop else practice): Write a program that checks if the word "apple" exists in the list ["banana", "orange", "grape", "kiwi"]. If found, print "Found!" and break. If not found, print "Not in list" using the else clause.

SolutionSolution
text = "Python Programming" for ch in text: if ch.lower() in "aeiou "ary> ```python fruits = ["banana", "orange", "grape", "kiwi"] for f in fruits: if f == "apple": print("Found!") break else: print("Not in list")

📚 Homework Questions

Write complete, well-commented Python scripts for each of these problems.

Question 1: The Prime Early Exit Write a program that asks the user for an integer n > 1. Using a for loop, check if n is prime. You only need to check divisors from 2 to int(n**0.5) + 1. As soon as you find a divisor, print "Not Prime" and break. If the loop finishes without finding a divisor, print "Prime" (using the else clause).

Sample Answer
n = int(input("Enter n: ")) import math is_prime = True for d in range(2, int(math.isqrt(n))+1): if n % d == 0: print("Not Prime") break else: print("Prime")

Question 2: The Guessing Game (Infinite until correct) Write a program that generates a random secret number between 1 and 100 (use import random; secret = random.randint(1, 100)). Use a while True loop to continuously ask the user for guesses. If they guess too low, print "Too low!"; if too high, print "Too high!". If they guess correctly, print "You got it!" and use break to exit the loop.

Sample Answer
import random secret = random.randint(1,100) while True: guess = int(input("Guess: ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print("You got it!") break

Question 3: Clean Data Filtering You are given a dirty list: data = [15, "hello", 42, None, 3.14, True, 99, "world", 0]. Write a program that iterates through this list using a for loop. Use continue to skip any item that is not an integer (use if type(item) is not int:). For every integer found, print the integer's square (e.g., 15 -> 225).

Sample Answer
data = [15, "hello", 42, None, 3.14, True, 99, "world", 0] for item in data: if type(item) is not int: continue print(item * item)

Question 4: The Interactive Menu System Write a program that displays a menu to the user:

1. Say Hello 2. Say Goodbye 3. Exit

Use a while True loop. Ask the user for their choice using input().

Sample Answer
while True: print("1. Hello\n2. Goodbye\n3. Exit") choice = input("Choice: ") if choice == '1': print("Hello!") elif choice == '2': print("Goodbye!") elif choice == '3': print("Exiting...") break else: print("Invalid choice")

Question 5: The Vowel Stripper (Nested Loops Challenge) Write a program that takes a list of words: words = ["apple", "sky", "banana", "cry", "ooooo"].

Sample Answer
words = ["apple", "sky", "banana", "cry", "ooooo"] for word in words: result = "" has_vowel = False for ch in word: if ch.lower() in "aeiou": has_vowel = True continue result += ch if not has_vowel: print(f"NO VOWELS: {word}") else: print(result)

Congratulations! You have mastered the art of flow control in loops. You now know how to iterate precisely (for), repeat based on conditions (while), and manipulate the flow (break/continue). These three tutorials form the bedrock of logical repetition in Python. On to the next unit!

Previous | Tutorial index | Next