Today, we’re expanding our concept map with the concept of loops in Python! Unless you’re a complete beginner, you probably know a thing or two about loops, but maybe I can teach you something new.
Table of Contents
- Concept Overview
- How Do I Replicate a Traditional Loop in Python?
- How Do I End a Loop Early Or Skip a Cycle?
- Loop Hero
Concept Overview
Recently, I talked about how snake case is one of the most basic concepts I will probably cover in this series. However, it has a few rivals. One of which is today’s concept: loops.
In the broadest sense, a loop is a tool for repeating a chunk of code. There are basically two ways to do this: a definite loop and an indefinite loop. As the name suggests, you use a definite loop when you know how many times you want to repeat a chunk of code. In contrast, you use an indefinite loop when you don’t know how many times you want to repeat a chunk of code.
In practice, definite and indefinite loops are more often colloquially described as for loops and while loops, respectively. In other words, a for loop can be configured to repeat a chunk of code as many times as you’d like. Meanwhile, a while loop is usually configured to repeat a chunk of code until some condition is met.
In Python, these definitions get muddied a bit because Python doesn’t have a traditional for loop. Instead, it has a for-each loop, which works by repeating a chunk of code for the number of items in a collection. It’s still a definite loop in the sense that the number of cycles is tied to the number of items in the collection, as seen below:
colors = ["red", "yellow", "orange"] for color in colors: print(color) # Prints # red # yellow # orange
In contrast, Python has a traditional while loop, which works by supplying some condition. As long as the condition is true, a while loop will continue to repeat a chunk of code. It’s possible that the condition never becomes false, so we end up with an indefinite loop that has become an infinite loop. Both of which are possible in the following code snippet:
text = input("Type stop to exit loop: ") while text != "stop": text = input("Wrong phrase! Type stop to exit loop: ") print("Congrats! You stopped the loop.")
Naturally, upon seeing this concept, you might have a few questions. In the rest of this article, we’ll look at them.
How Do I Replicate a Traditional Loop in Python?
A natural follow up question to learning that Python doesn’t support traditional loops might leave you with some concern. Luckily, traditional loops can be replicated with the enumerate()
function. Given a collection, this function provides both the index and the item, rather than just the item. That way, you can treat lists just like you normally would in other languages, as seen below:
colors = ["red", "yellow", "orange"] for i, color in enumerate(colors): print(i, color) # Prints # 0 red # 1 yellow # 2 orange
If you’re wondering how this works, enumerate()
basically creates a tuple in the form (index, item), which you then can deconstruct using iterable unpacking. You can observe this process directly by removing the iterable unpacking from the loop:
colors = ["red", "yellow", "orange"] for pair in enumerate(colors): print(pair) # Prints # (0, 'red') # (1, 'yellow') # (2, 'orange')
If you’re not working with a collection of data at all, don’t worry! There is also the range()
function, which let’s you specify a range of numbers to iterate through. In other words, if you’re familiar with the traditional loop syntax of some initializer, a condition, and an incrementor, you can accomplish the same thing with a simple function call, as shown below:
for i in range(0, 5): print(i) # Prints # 0 # 1 # 2 # 3 # 4
The range()
function is very flexible and allows for a lot of different ways to iterate through a range of numbers. For example, if you want to iterate over odd values only, you can set the step to two.
for i in range(3, 9, 2): print(i) # Prints # 3 # 5 # 7
How Do I End a Loop Early Or Skip a Cycle?
Like most programming languages, Python has support for both the break
and continue
keywords, which exist to end a loop early or skip a loop iteration, respectively. Typically, for these to work, they need to be accompanied by a condition themselves. For example, we might write a loop that searches a collection for a specific item. In which case, we could break out of the loop as soon as we find it:
colors = ["red", "yellow", "orange"] for color in colors: if color == "yellow": break
Alternatively, maybe we want to skip some expensive computation if the right conditions aren’t met. In that case, we might use the continue
keyword:
colors = ["red", "yellow", "orange"] for color in colors: if color != "yellow": continue # Expensive operation
In general, you’ll probably hear that using either keyword is considered bad practice. My opinion tends to be that there’s a right place and right time for everything, but I would recommend limiting your use of either keyword as much as possible. Typically, at least with indefinite loops, the loop condition should be doing most of the heavy lifting.
At the end of the day, it’s up to you to decide what makes sense. I’d recommend some of these threads that include the opinions of others:
Some folks make theoretical arguments against break with respect to loop invariants, but I don’t subscribe to the logic. I do, however, have a disdain for flags in loop conditions. In those cases, I would much rather see break
or continue
.
Loop Hero
You may recall that I’ve written about how to write a loop in Python already. As a result, I won’t rehash too much of that content, so let’s call it here today. Maybe in the future we’ll talk about recursion! That could be a fun related concept to add to the concept map.
In the meantime, I’d love for you to take a look at one of these related articles:
- What Value Does X Have at the End of a Loop in Java?
- How to Loop Over a Dictionary in Python: Keys, Values, and More
- Loop Syntax and Design in Java
Likewise, feel free to browse some of these related resources (#ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
And, you can even take your support a step further by checking out my list of ways to grow the site. Otherwise, as always, take care! See you soon.
Recent Posts
Recently, I was thinking about the old Pavlov's dog story and how we hardly treat our students any different. While reflecting on this idea, I decided to write the whole thing up for others to read....
In the world of programming languages, expressions are an interesting concept that folks tend to implicitly understand but might not be able to define. As a result, I figured I'd take a crack at...