Comparing Python's for and while loops

Here's when you should use one over the other

Loops are essential tools in Python, allowing us to execute blocks of code repeatedly with minimal effort. But not all loops are created equal.

Python’s two main types of loops - for and while - each serve distinct purposes and are best suited for different scenarios. Knowing when to use one over the other can streamline your code and make it more efficient.

In this article, we’ll explore the key differences between for loops and while loops, look at real-world examples for each, and dive into a practical case where both types of loops can be combined for maximum flexibility.

The For Loop

Python’s for loop is a control flow statement that allows you to execute a block of code repeatedly for a predetermined number of times. This type of loop iterates over a collection, such as a list, string, range, and more.

If you’ve ever taken an introduction to Python course, you’ve absolutely talked about these kinds of loops before discussing while loops. Chances are in practice as well, you’ll use the for loop significantly more than while loops.

You most likely have seen it structured as such:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

The While Loop

The while loop can be slightly tricky: it’s designed to loop until a certain condition is met. Think of it as a funky if statement from a logical perspective: “If I meet condition X, then I want to stop looping”.

A more common example that is taught in Computer Science classes at universities is the number guessing game, where the user has to continually input a number until they get it right:

# Looping until a user guesses the correct number
correct_number = 7
guess = None

while guess != correct_number:
    guess = int(input("Guess the number: "))
    if guess < correct_number:
        print("Too low, try again.")
    elif guess > correct_number:
        print("Too high, try again.")

print("You've guessed the number!")

Here, it doesn’t make sense to use a for loop, as you don’t know how many times the user is going to guess. However, you could modify the code so that they only get a certain number of tries.

The Differences

The major difference between the two is what you’re iterating over:

  • A for loop is used when you know the number of times you need to loop. You’ll iterate over a data structure such as a list or tuple.

  • A while loop is used when you don’t know the number of times you need to loop. You’ll continue to loop over a block of code until a certain condition is met.

An Example of Using Both

I’m currently writing some code for my newsletter clients that performs backups of their data. The API only returns 100 subscribers at a time at most, which means I need to make multiple requests to the API several times in order to get their full list.

However, I don’t know how many subscribers they have with only this API request, so I throw this in a while loop so it goes until there’s no subscribers that are returned from the API.

If there are subscribers, then I want to go through and process them accordingly. The API does tell me how many I have, so I opted to use a for loop in this scenario.

Below is a skeleton of what this code looks like:

while True:
    # Get the list of subscribers
    response = requests.get(
        url, 
        headers = headers, 
        params = params
    )
    
    response = response.json()

    # If there's no more subscribers, then we exit
    #   out of the loop.
    if len(response['data']) == 0:
        break
    
    # If there are subscribers still, then perform
    #  backup.
    for subscriber in response['data']:
         # perform data cleansing, etc.

📧Join the Python Snacks Newsletter!🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.