Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Loop Control: For, While, Break, and Continue

Recommended resources

Hello! In our last lesson, we explored how if, elif, and else statements give our programs the ability to make decisions and execute different code paths. This was our first step in moving beyond simple, top-to-bottom script execution.

Today, we'll unlock another fundamental capability: repetition. Often in programming, you need to perform the same action multiple times. Instead of writing the same code over and over, we can use loops. This lesson will introduce you to Python's two main types of loops: the for loop, for repeating a task a specific number of times, and the while loop, for repeating a task as long as a certain condition holds true. We will also learn how to fine-tune their behavior with the break and continue statements.

The for Loop: Definite Iteration

The for loop is your tool of choice when you want to iterate over a known sequence of items, such as the characters in a string or the items in a list. Because you know the collection of items you're working with beforehand, this is often called definite iteration.

The basic idea is "for each item in this collection, do something." Let's watch a video that visually breaks down how a for loop works and how to use it to iterate through various sequences.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This video from the "Data with Baraa" channel provides excellent visual explanations for loop mechanics, which is perfect for building a strong mental model.

First, watch the conceptual explanation of what a for loop is and how it processes a sequence from the start. Then, continue with the practical examples of iterating through lists, strings, and using the range() function from the examples. Pay close attention to how the range() function's start, stop, and step arguments work.

As you saw, the range() function is incredibly useful. It allows you to generate a sequence of numbers without having to type them all out, making it easy to run a block of code a specific number of times.

Here's a quick recap of the range() syntax:

  • range(stop): Generates numbers from 0 up to (but not including) stop.
  • range(start, stop): Generates numbers from start up to (but not including) stop.
  • range(start, stop, step): Generates numbers from start up to stop, incrementing by step.

The while Loop: Indefinite Iteration

What if you don't know how many times you need to loop? What if you need to repeat an action until a certain condition changes, like waiting for user input or processing items until a specific value is found? This is where the while loop comes in. It performs indefinite iteration.

A while loop repeatedly executes a block of code as long as a given condition is True. This ties in perfectly with what you learned about conditional expressions in the last lesson.

There are three critical components to a standard while loop:

  1. Initialization: A variable is set to an initial value before the loop starts.
  2. Condition: The while statement checks this variable in a condition that evaluates to True or False.
  3. Update: Inside the loop, the variable is updated. If you forget this step, the condition might never become False, leading to an infinite loop that can crash your program!

Let's watch a short video that demonstrates a basic while loop and highlights these components.

Python While Loops & For Loops | Python tutorial for Beginners

This clip from Dave Gray's tutorial is a concise and clear demonstration of a while loop used as a counter.

Watch the segment from the beginning that explains and codes a basic while loop. Notice how the value variable is initialized, checked in the condition, and incremented inside the loop.

A common and powerful pattern is to create a deliberately infinite loop with while True: and then use a conditional if statement inside the loop to break out of it. This can often make the logic for exiting the loop clearer.

For instance, this pattern is great for continuously prompting a user for input until they enter a specific word to quit.

while True:
    command = input("Enter a command ('quit' to exit): ")
    if command == 'quit':
        break
    print(f"You entered: {command}")

print("Loop finished.")

Controlling Loops: break and continue

Sometimes you need more control over your loops than just letting them run their course. Python gives us two statements to manage the flow from within a loop: break and continue.

  • break: Immediately terminates the loop. The program's execution jumps to the very next statement after the loop block. It's an emergency exit.
This flowchart shows how a `break` statement provides an immediate exit path from a loop's execution cycle.
  • continue: Immediately stops the current iteration and jumps to the next one. The loop itself keeps going, but the rest of the code in the current iteration is skipped.

To see these in action with clear, simple examples, let's turn to a textual resource.

Loops - Learn Python - Free Interactive Python Tutorial

This tutorial from learnpython.org provides very direct and easy-to-understand code examples for loop control.

Please read the section "break" and "continue" statements. Focus on the two examples: one showing break to stop a while loop when a count is reached, and the other showing continue to skip even numbers in a for loop.


Let's Practice

Now it's time to combine these concepts. Create a new Python file named loop_practice.py.

Problem:
You are given a list of numbers. Your task is to loop through the list and print only the even numbers. However, you must stop all processing and print nothing further if you encounter the number 237.

Here is the list to start with. Copy it into your script:

numbers = [
    951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
    615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105,
    942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328,
    615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950,
    626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81
]

Instructions:

  1. Write a for loop to iterate through the numbers list.
  2. Inside the loop, first check if the current number is 237. If it is, use the break statement to exit the loop.
  3. Next, check if the number is odd. A number is odd if the remainder when divided by 2 is not 0 (number % 2 != 0). If it is odd, use the continue statement to skip to the next number.
  4. If the number has passed both checks (it's not 237 and it's not odd), then print it.

Try to solve this on your own before looking at the solution.

Click to see the solution
numbers = [
    951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
    615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105,
    942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328,
    615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950,
    626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81
]

for number in numbers:



    # If we find 237, stop everything.
    if number == 237:
        break




    # If the number is odd, skip to the next iteration.
    if number % 2 != 0:
        continue
    



    # If we've made it this far, the number is even. Print it.
    print(number)

Your output should be:

402
984
360
408
980
544
390
984
592
236
942
386
462
418
344
236
566
978
328
162
758
918

Conclusion

In this lesson, you've gained the power of repetition, a cornerstone of programming that allows you to automate tasks and handle collections of data efficiently.

Here are the key takeaways:

  • for loops are for definite iteration: use them when you have a sequence (like a list, string, or a range) and want to perform an action for each item.
  • while loops are for indefinite iteration: use them when you want to repeat an action as long as a condition remains true. Be mindful of infinite loops!
  • break provides a way to exit a loop immediately, regardless of the loop's condition.
  • continue lets you skip the current iteration and jump to the next one.

We've used lists quite a bit today as the sequence for our for loops. In the next lesson, we will dive much deeper into lists, exploring how to create, access, modify, and manage them. They are one of Python's most versatile and fundamental data structures.