Python Loops

flora marina petersen
3 min readJul 5, 2021

--

Let’s talk about loops in Python! Loops will help you simplify your code significantly. For example, if you want to send the same email to 10 people on a list, you don’t have to write a block of code for each person. Instead, you can use a single block of code to tell your program to go through the list and send an email to each person. This will save much time and memory!

In this post, we’ll talk about for loops and while loops.

A for loop is the type of loop you would use in the above example with the emails. When you use a for loop, you are telling your program: go through this list of things, and do something for each thing. That sounds pretty abstract, so let’s see what it would look like:

friends = ['Ted', 'Tod', 'Tad']
for friend in friends:
print('Hello, ' + friend + '!')

When we run this code, our output will look like this:

Hello, Ted!
Hello, Tod!
Hello, Tad!

Our for loop ran through the list, and executed the code inside the loop for each name on the list. Pretty simple, right? If we didn’t use a loop, what would our code look like?

print('Hello, Ted!')
print('Hello, Tod!')
print('Hello, Tad!')

Not too bad. That only took 3 lines of code, and we used 3 lines of code to write the loop. But that was for a list with only 3 names on it. What if the list had 1,235 names on it? You’d be pretty glad you knew how to write a for loop!

The next loop we’ll look at is the while loop. A while loop executes a block of code only while a certain condition is met. If that condition is not met, the next line of code outside the loop will be executed instead.

Here’s an example:

count = 0
while count < 5:
print(count)
print('All done!'

Now, we initially set count equal to zero. This while loop tells our program that as long as count is less than 5, we will print out the number. Once count is no longer less than 5, our program will exit the loop and say, “All done!” But wait, before we run the code… Will count ever be more than 5? Will it ever NOT be zero? As far as our program knows, it will be zero forever! That’s because we forgot to increment count in the loop. The problem with something like this is that it creates an infinite loop. If the condition is satisfied forever, then the program will continue executing the code in the loop… forever. This might make your computer (and you!) very unhappy. So, let’s increment count inside the loop!

count = 0
while count < 5:
print(count)
count = count + 1
print('All done!'

There we go! Now, every time the loop prints out count, it will then add one more to count. So, eventually, count will be more than 5. Let’s run this code and see what we get:

0
1
2
3
4
All done!

Awesome! Our program printed out count, until count reached 5. Then, it exited the loop and executed the next line of code to tell us that it is all done. And now we are all done with this post! Thanks for reading!

--

--

No responses yet