KAHIBARO Bookshelves
Discord Login Register

7.5. break and continue

Breaking out of loops with `break`

Sometimes you don’t want a loop to run all the way to the end. You may want to:

  • Stop as soon as you find what you’re looking for
  • Exit early when a certain condition happens
  • Avoid running useless extra iterations

The break statement lets you immediately stop the current loop.

When Python sees break inside a loop:

  1. It stops the loop right away (even if the loop condition is still True or values are left to iterate over).
  2. It jumps to the first line after the loop.

Basic pattern:

while condition:
    # some code
    if stop_condition:
        break
    # more code

or

for item in collection:
    # some code
    if stop_condition:
        break
    # more code

Example: stop when a number is found

numbers = [3, 8, 12, 5, 7, 12, 9]
target = 12
for n in numbers:
    print("Checking:", n)
    if n == target:
        print("Found it!")
        break
print("Loop finished.")

Output:

Checking: 3
Checking: 8
Checking: 12
Found it!
Loop finished.

Even though there are two 12 values in the list, the loop stops after finding the first one.

Using `break` in a `while` loop

You can also use break to stop a while loop that would otherwise keep going.

while True:  # infinite loop on purpose
    text = input("Type 'exit' to quit: ")
    if text == "exit":
        print("Goodbye!")
        break
    print("You typed:", text)

Here, while True creates a loop that could run forever, but break gives us a controlled exit when the user types "exit".

`break` in nested loops

When you use loops inside loops (nested loops), break only stops the innermost loop where it appears.

for i in range(3):
    print("Outer loop i =", i)
    for j in range(5):
        if j == 2:
            print("  Inner loop breaking at j =", j)
            break
        print("  Inner loop j =", j)

Output:

Outer loop i = 0
  Inner loop j = 0
  Inner loop j = 1
  Inner loop breaking at j = 2
Outer loop i = 1
  Inner loop j = 0
  Inner loop j = 1
  Inner loop breaking at j = 2
Outer loop i = 2
  Inner loop j = 0
  Inner loop j = 1
  Inner loop breaking at j = 2

The break only exits the for j in range(5) loop. The outer loop over i keeps running.

If you need to stop all loops, you typically:

  • Use a flag variable
  • Or return from inside a function (once you know functions)

Example with a flag:

found = False
for i in range(3):
    for j in range(3):
        if i == 1 and j == 2:
            found = True
            break  # breaks inner loop only
    if found:
        break      # breaks outer loop
print("Stopped at i =", i, "j =", j)

Skipping to the next iteration with `continue`

Sometimes you don’t want to stop the loop, but you want to skip the rest of the current iteration and move on to the next one.

The continue statement does exactly that:

  • It skips any remaining code in the loop body for the current item/iteration
  • It jumps back to the top of the loop and starts the next iteration (if any)

Basic pattern:

for item in collection:
    # some code
    if skip_condition:
        continue
    # this code is skipped when skip_condition is True

or

while condition:
    # some code
    if skip_condition:
        continue
    # more code that might be skipped

Example: skip negative numbers

numbers = [3, -2, 5, -7, 10]
for n in numbers:
    if n < 0:
        # Skip negative numbers
        continue
    print("Processing:", n)

Output:

Processing: 3
Processing: 5
Processing: 10

The negative numbers are ignored; the loop continues with the next element.

Using `continue` in a `while` loop

Be careful with continue in while loops: you must still make sure the loop condition can change, or you might create an infinite loop.

n = 0
while n < 5:
    n += 1
    if n == 3:
        # Skip number 3
        continue
    print("n is", n)

Output:

n is 1
n is 2
n is 4
n is 5

Notice we increment n before the continue. If we moved n += 1 to after the continue, the loop might never reach 5.

Combining `continue` with other logic

continue is useful when you want to:

  • Skip invalid or unwanted inputs
  • Ignore special cases
  • Keep your code less deeply indented

Without continue:

for n in range(10):
    if n % 2 == 0:
        print("Even:", n)

With continue and extra logic:

for n in range(10):
    if n % 2 != 0:
        # Skip odd numbers
        continue
    print("Even:", n)

Both versions print even numbers, but the continue approach is sometimes clearer when there are more conditions and more code.

Comparing `break` and `continue`

break and continue both affect how loops run, but in different ways:

  • break:
    • Ends the loop completely
    • Execution continues after the loop block
  • continue:
    • Skips the rest of the current iteration
    • Goes back to the top of the loop for the next iteration

Example showing both:

for n in range(1, 10):
    if n == 7:
        print("Stopping loop at", n)
        break              # stop completely when n is 7
    if n % 2 == 0:
        continue            # skip even numbers
    print("Odd number:", n)

Output:

Odd number: 1
Odd number: 3
Odd number: 5
Stopping loop at 7

Flow:

  • For even numbers, we skip the print("Odd number:", n) line.
  • When n reaches 7, we never reach the continue; instead we break and finish the loop.

Common patterns with `break` and `continue`

1. Searching with early exit (`break`)

names = ["Alice", "Bob", "Charlie", "Diana"]
search = "Charlie"
found = False
for name in names:
    if name == search:
        found = True
        break
if found:
    print(search, "was found in the list.")
else:
    print(search, "was not found.")

break saves time by stopping as soon as we find the match.

2. Filtering values (`continue`)

values = [0, 10, -5, 3, 0, 8]
for v in values:
    if v == 0:
        # skip zeros
        continue
    print("Non-zero value:", v)

We only process the non-zero values.

3. Simple menu with exit option (`break`)

while True:
    print("Menu:")
    print("1. Say hello")
    print("2. Say goodbye")
    print("3. Exit")
    choice = input("Choose an option (1-3): ")
    if choice == "1":
        print("Hello!")
    elif choice == "2":
        print("Goodbye!")
    elif choice == "3":
        print("Exiting...")
        break
    else:
        print("Invalid choice.")

Here break cleanly exits the loop when the user picks option 3.

When to avoid `break` and `continue`

break and continue are useful, but overusing them can make code harder to follow.

Guidelines:

  • It’s fine to use them for clear, simple control flow, like:
    • Exiting a menu
    • Stopping a search early
    • Skipping invalid items
  • Avoid sprinkling many break/continue statements throughout long loops. If the flow starts to feel confusing, consider:
    • Splitting logic into functions
    • Using clearer conditions in the loop header
    • Using variables (flags) to express state

As you practice, you will get a feel for when break and continue make your code easier to read, and when they make it more complicated.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms