A Guide to Types of Loops in Python

You can access the full course here: Python Foundations

While Loops

Now that we can perform tests and execute code once, the next step is to be able to perform tests and execute code multiple times as long as some condition continues to be true. For this, we use loops. Loops provide a way to execute code multiple times without having to type the same code again and again.

The simplest form is the while loop and it acts very much like an if statement run multiple times. It performs a test and executes code if the test returns True but instead of executing the code once, it continuously executes the code until the test eventually returns False. This can be dangerous because if the test never returns False, the loop will run infinitely and the program will crash so we need to make sure that we build the loop in such a way that it will eventually exit.

Games at their heart, often contain a big game loop that continuously performs checks, handles player interaction, renders graphics, etc. as long as the game is still running and breaks when the user does something to end the game. We can build a very very simplified version of this by moving a player as long as they are not quite at the end position and then exiting the loop when they are. We first need current and end position variables:

pos = 0
end_pos = 5

Then we need a way to check if we are at the end pos and if not, move our player forwards. An if statement will only do it once so we need a loop which loops like this:

while pos < end_pos:
  pos += 1
  print(pos)

Note the same indentation style as the if statement and how similar it looks and feels. The difference is that the while loop loops to the top and executes the test and code continuously until eventually, in our case, the pos >= end_pos. In this case, it will run 5 times. We know that this will eventually stop because our pos < end_pos at the start and we’re increasing it by 1 each time.

For Loops

The next type of loop is the for loop. This acts the same as a while loop but it runs a preset number of times. We build right into the loop when to start and when to stop so we know how many times it will run. We can pair it with a collection type to run a set number of times with a range or to visit every element of a list or dictionary. When we pair it with a list, for example, we iterate through the list with each iteration of the loop visiting the next element of the list. We can visit every member of a list and print it out with a for loop like this:

inventory = [“Axe”, “Helmet”, “Bread”]
for item in inventory:
  print(item)

Note again, the indentation. This loop has set the collection to be inventory so it starts with the first element and ends with the last. Each element it visits is stored in the item variable. We then print out the value stored in the item variable for each iteration: first “Axe”, then “Helmet” and so on. We can also pair for loops with ranges if we just want them to run a set number of times. For example, if we wanted a loop to print “Hello” 5 times, we could do so like this:

for i in range(5):
  print(“Hello”)

We don’t really care so much about i, we just want the loop to run 5 times so it runs as many times as there are elements in the range. The final thing about loops is that every for loop can be turned into a while loop but not every while loop can be turned into a for loop because sometimes we don’t know how many times a while loop will run but we always know how many times a for loop will run.

Transcript

While Loops

Hello everyone. Welcome to our tutorial on while loops. This will be our first intro into the concept of loops, so we’ll take some time to explain what they are and take a look at some examples.

So we’re going to start with what are loops and what are specifically while loops, how do they work? And then we’ll write and run a simple while loop. This is an important part of game development, so if you’re interested in developing games, this is a great place to really pay attention. Let’s head to the code and get started.

All right, so what is a loop? Well, a loop in programming allows us to execute the same code multiple times without having to write it multiple times, okay? The concept is that we write it once and we tell the loop how many times to run and then it executes the code that many times.

Okay, this isn’t so much of a problem if we only have like a couple of lines of code that we want to execute a few times. But if, for whatever reason, we want that code to run 100 or 1,000 times, that’s gonna be horrible to have to write that all out by hand and that’s really poor code practice to be repeating code that many times. The idea is that you put it in a loop, you set it to run 1,000 times and then it does the work for you.

So a simple while loop actually looks very similar to an if statement, except that instead of if, and then a test, we have while and then the test. So then we have while test and then code to execute, okay? So it works the same way but just multiple times potentially. So we’ll perform some test, usually comparing variable values. If that is true, we execute the code.

The difference is with an if statement, it would end here and then go on to execute any code down here. However, with a while loop, it will loop back up to the top and then it’ll perform the test again. If it’s true, it executes the code, and loops back to the top and it keeps doing this over and over again until eventually this is false. That means we have to make sure that these while loops eventually will exit otherwise you just get them running endlessly, okay?

So a simple example, and is often used in basic game loops, would be to check to see if we have reached the end condition. So if we’re building a simple like move left and right-type game, we might have kind of like a platformer game, we might have a position and we’ll just stick with position because we’re not worried about y positions for now. And maybe we’ll start at zero, okay? And we’ll have some kind of end goal or an end position and maybe we’ll set this equal to five. So our goal is to carry out a set of commands or basically run the game as long as we haven’t reached the end position.

So we might do something like this. While our current position is less than our end position, then we’ll execute the code. Okay, as soon as this is no longer true, that means we have reached our end position or perhaps gone past it, at which case, our game should be over as we’ve kind of won. So in our case, we’ll just do something really, really simple. We’ll just increase our current position by one, so we’re moving right all the time, and then we’ll maybe print out the position.

Realistically, you’d handle any other game logic in here, such as the actual player commands, whether you’re moving left and right. You’d also do stuff like collision detection, any other kind of game logic that need to be implemented but we’re not really building a game. This is just a really quick example.

So we can go ahead and run this and you can see that we’re getting this printed five times, the numbers one through five. The reason being that we start out with position equal to zero and end position is always gonna be five. We increase it by one, so position is now one. And then we print it out. Then we reach the end of the loop, we go back to the top, position is one. That’s still less than five and so we execute the code again and again and again and we keep doing this until eventually position is equal to five. Then we loop to the top five, it’s not longer less than five and so then we exit out of the loop and then we’d execute any other code down here.

Note again the indentation style rather than using curly brackets, okay? So that’s very important. If you want to exit the loop, and write any code afterwards, just make sure that it doesn’t have the same indentation. Make sure that it is over on the edge again.

Okay, so that’s pretty much it. That’s a really quick intro into loops. This is something that if you didn’t quite get it from this explanation, you’re definitely want to try this out and try to go over some examples of your own. Loops are really quite a fundamental part of programming and can be a little confusing so definitely give this a practice.

Just make sure that at some point your loop will exit. If it has no kind of exit condition, for example, if I was never increasing my position by one, the loop would run infinitely and that’s a problem. Okay, so when you’re ready to move on, we’ll cover a second type of loop which is the for loop or in Python, it’s actually a for in loop, but more on that in the next one.

So stay tuned for that. Thanks for watching, see you guys in the next one.

For Loops

What’s up guys? Welcome to our tutorial on for loops. This is the second type of loop we’ll be covering, so make sure that you’re comfortable using while loops before moving to this one, as these ones can be a bit more complex. So we’ll start by covering what are for loops, then we’ll write and run a simple example, and then we’ll compare them to while loops and talk about when and where we would use each one. Let’s head to the code and get started.

All right. Let’s talk about for loops and how they’re different from while loops. Well, a for loop is another kind of loop, which means it’s just a way to execute code multiple times. The difference is, a for loop typically has a predefined start and end point. So we always know exactly how many times the loop is going to run, or at least we know the maximum number of times it will run. So this prevents us from getting stuck in an infinite loop, like with a while loop where the end condition is never gonna evaluate to false.

Now, because we know exactly how many times these are going to run, they’re often paired with lists or ranges because we can use a range, for example, to specify exactly how many times a for loop will run, or we can use a for loop with a list to iterate through each element. So we’ll take actually look at an example of both.

I’ll set up a very simple list. Oops! Not variable. I just want my inventory. And I’m just gonna set it equal to some items. Let’s have, again, start with an axe. Feeling a little uncreative today. We’ll do a knife, and then we’ll do like a helmet. Okay. So we got three items.

If we want to iterate through each of them and print them out, I could do print out inventory of zero, inventory of one, two, et cetera. But if there were a hundred items, that’s gonna be really tedious. Instead, I could use a for loop and say something like for item in inventory, print item. And that is all I need to do. That way, if there were a hundred elements, I could print out all a hundred of them with two lines of code.

Now the reason that this works is because we are looking for everything in this collection type. So in this case, it’s a list. And so it says, ” Okay, this list has three elements in it. “We’re going to iterate through “and visit each one three times.” And each time we iterate through, we’re assigning the value that we’re on into this variable called item.

So for the very first pass, it will get to the first item. Axe, and it will sign that to item. And then we’ll print the item, which contains a value of axe. Then it gets to the second loop iteration. Says,” Okay, what’s the second element?” It’s a knife, assigns it here and prints out. What’s the third element? Helmet, prints out, et cetera. And then it reaches the end and it exits. And it does all of this automatically. All right?

So if we actually don’t have a list to pair our for loop with, and we just want to run some code a certain number of times, we typically use a range. So we would say something like for I in range from zero up until let’s say we want to run something five times, we would say from zero to five. And then we would say maybe print, I don’t know, print I. So nothing very exciting. So we go ahead and run that, and you can see that we’re getting I printed out five times. We start at zero because that’s our start point in the range. We end at four because our range goes until five, but again, the top upper bound is not included, and then we’re just printing I out. Okay?

So this is very useful if again, we’re not iterating through a list, we just wanna run something a certain number of times. This is great if we’re iterating through a list specifically, and then we would use a while loop, if we don’t know exactly how many times we want to run.

For example with a game loop, you’re typically looping through a set of actions and updating the game, also handling user interactions, collision detection, all of that stuff, but you’re constantly doing it as the game runs. That’s typically inside of some big while loop. Because we don’t know exactly how many times it will run. Whereas with a full loop, we always know exactly how many times it will run and that’s why we specify our start and end points.

So play around with this a bit, maybe try some for loops with lists, maybe try some with just ranges and doing something a certain number of times. When you’re ready to move on, we’ll switch topics and talk about functions. So stay tuned for that. Thanks for watching and see you guys in the next one.

Interested in continuing? Check out the full Python Foundations course, which is part of our One-Hour Coder Academy.