Skip to main content

Welcome to a Grasp lesson

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

Lesson 5

Controlling Iteration with `for` and `while` Loops

Recommended resources

Hello! Welcome to your fifth lesson on the fundamentals of programming.

In our last lesson, you learned how to use conditional statements (if, elif, else) to control the flow of your program, allowing it to make decisions. This was a huge step in making your code "intelligent."

Today, we'll explore another fundamental type of control flow: iteration, or more simply, loops. Loops allow you to execute a block of code repeatedly, which is the cornerstone of automating repetitive tasks and processing collections of data—both essential skills for designing algorithms.

By the end of this lesson, you will be able to write for and while loops to control iteration in your programs.

Python For Loop Visual Metaphor
This image provides a great visual metaphor for a `for` loop: a machine that processes items from a sequence one by one, with controls like 'break' and 'continue' to manage the process.

1. The while Loop: Repeating Based on a Condition

The first type of loop we'll explore is the while loop. Its logic is very similar to an if statement: it executes a block of code as long as a certain condition remains True.

A while loop has three essential components:

  1. Initialization: A variable that is set up before the loop starts.
  2. Condition: The test in the while statement that evaluates to True or False. The loop continues as long as it's True.
  3. Update: A statement inside the loop that modifies the initialization variable. This is crucial to ensure the condition eventually becomes False, otherwise you'll create an infinite loop that never ends!

Let's watch a video that demonstrates this structure clearly.

Python While Loops & For Loops | Python tutorial for Beginners

This clip from Dave Gray's tutorial shows how to construct a basic while loop. Notice the initialization, the condition, and the crucial increment step inside the loop.

Watch from 00:50 to 02:32.

As you saw, a typical while loop looks like this:




# 1. Initialization
count = 1




# 2. Condition
while count <= 5:
    print(count)



    # 3. Update
    count = count + 1  # or count += 1

print("Loop finished.")

This code will print the numbers 1, 2, 3, 4, and 5. Once count becomes 6, the condition 6 <= 5 is False, and the loop terminates.

Hands-On Practice 1: Countdown

Let's practice this. In a new Python file, write a while loop that counts down from 5 to 1 and then prints "Liftoff!".

Click here for the solution
number = 5

while number > 0:
    print(number)
    number = number - 1

print("Liftoff!")


2. The for Loop: Repeating for Each Item in a Sequence

While while loops are great for repeating an action until a condition is met, for loops are designed to iterate over a sequence of items. Think of it as "for each item in this collection, do this." The collection could be a list of names, the characters in a string, or a sequence of numbers.

Let's see how to use a for loop to iterate through a list of names and the characters of a string.

Python While Loops & For Loops | Python tutorial for Beginners

This segment shows the basic syntax of a for loop. Pay attention to how the loop variable (x in the video) takes on the value of each item in the sequence, one by one.

Watch from 05:37 to 07:26.

Generating Number Sequences with range()

A very common task in algorithms is to repeat an action a specific number of times. Instead of creating a list of numbers manually, you can use Python's built-in range() function. It's highly efficient for generating number sequences.

The range() function can be used in a few ways:

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

Since you have a solid math background, the start, stop, and step arguments should feel quite intuitive. Let's see it in action.

Python While Loops & For Loops | Python tutorial for Beginners

This part of the video explains how to use range() to control for loops, which is an extremely common pattern in Python.

Watch from 08:49 to 11:30.

Hands-On Practice 2: Finding Even Numbers

Use a for loop with the range() function to print all the even numbers from 2 to 20, inclusive.

Hint: Think about the start, stop, and step arguments for range().

Click here for a solution



# The range goes up to 21 because the stop value is not included.
# The step is 2 to only get even numbers.
for number in range(2, 21, 2):
    print(number)

Note: You could also solve this by looping through every number from 2 to 20 and using an if statement to check if the number is even (if number % 2 == 0:), but using the step argument is more direct.



3. Controlling Loops with break and continue

Sometimes you don't want a loop to run to completion. Python gives you two powerful statements to control the flow within a loop:

  • break: Immediately terminates the loop and the program continues at the next statement after the loop.
  • continue: Immediately stops the current iteration and jumps to the beginning of the next one.

Let's see how break and continue work inside both while and for loops.

Python While Loops & For Loops | Python tutorial for Beginners

This video demonstrates how break can stop a loop prematurely and how continue can skip an iteration. The examples are shown for both loop types.

Watch from 02:32 to 04:32 (for while loops) and then from 07:26 to 08:49 (for for loops).

Here's an image showing a clear example of continue in a while loop.

Python While Loop with Continue Statement
This code uses a `while` loop to count down. The `continue` statement causes the loop to skip printing when `num` is 0.

Hands-On Practice 3: Upgrading the Guessing Game

Let's apply these concepts by improving the number guessing game from the last lesson.

  1. Take your "Guess the Number" code.
  2. Wrap the entire guessing logic inside a while True: loop. This creates an infinite loop, allowing the user to guess multiple times.
  3. Inside the loop, if the user guesses the correct number, print a success message and then use the break statement to exit the loop.
Click here for the solution
secret_number = 7

while True:  # This will loop forever until a 'break' is hit
    guess_str = input("Guess a number between 1 and 10: ")
    guess = int(guess_str)

    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print("You got it!")
        break  # Exit the loop on correct guess

print("Thanks for playing!")


4. for vs. while: Which One to Choose?

This is a common question for beginners. Here's a simple rule of thumb:

  • Use a for loop when you know in advance how many times you need to loop, or when you want to iterate over a collection (like a list or a string). This is called definite iteration.
  • Use a while loop when you need to loop as long as a certain condition is true, and you don't know how many iterations it will take. For example, waiting for user input or processing data until a specific value is found. This is called indefinite iteration.

For a concise summary of best practices, take a look at the following resource.

An In-Depth Guide to Python Loops

This article provides excellent best practices for using loops. Focus on the points that help you decide between a for and a while loop.

Read the "Best Practices" section. Pay special attention to the first, fourth, and last bullet points, which offer guidance on choosing the right loop and avoiding common pitfalls.


Final Challenge

To pull everything together, let's tackle a small challenge that requires a for loop, if statements, break, and continue.

Loops - Learn Python

This resource from learnpython.org provides a great practice exercise to test your understanding of loop control.

Read the exercise description under the "Exercise" heading. Try to solve it yourself in your Python editor before looking at the solution provided on the page. The goal is to loop through the numbers list and print only the even numbers, but stop entirely if you encounter the number 237.



Conclusion

Fantastic work today! You have now mastered the two fundamental loop constructs in Python, which are absolutely essential for building algorithms. You can now write code that repeats tasks, processes collections of data, and responds dynamically to conditions within the repetition.

Here are the key takeaways:

  • while loops execute a block of code as long as a condition is True. They are ideal for indefinite iteration.
  • for loops execute a block of code for each item in a sequence. They are perfect for definite iteration over lists, strings, or number ranges generated by range().
  • You must remember to update the condition variable in a while loop to avoid infinite loops.
  • break provides an "emergency exit" from a loop.
  • continue skips the current iteration and moves to the next.

In our next lesson, we will learn how to define and call functions. Functions will allow you to organize the code you've been writing into named, reusable blocks, making your programs more modular and easier to read. This is a critical step towards writing complex algorithms.