First off, did you have a good weekend? If you didn’t and need a little bit of inspiration for the week, check out my Pinterest “Quote of the Day” board. It has a bunch of inspirational/motivational quotes from some of my biggest inspirations. Anyway, today we’re going to talk about loops.
So what is a loop? It allows you to tell python how many times you want it to run a bit of code. Ok, what does that mean?
For example, lets say we wanted to create a guess the number game. We would want the user to keep entering numbers until they guess the right number or until the number of guesses reaches some limit. We would need a code to keep track of the users guesses, check if the number they guessed is correct, repeat until the user wins or loses, and stop once the number of guesses reached the limit.
That seems like a lot. Here’s the thing though, that the code we’re about to build! First lets go over loops.
Like I said, loops let us run the same code a number of times and end when we tell them to end. There are two types, the while loop and the for loop.
The While Loop
To use a while loop, we literally use the keyword “while”. Here’s what it looks like:
- while this is true:
- do this
If you read my post on if statements (if you didn’t, click here), you’ll see that the formatting is the same. Remember that after using the while statement you need a colon, and any code inside of it needs to have an indent in front.
One of the great things about a while loop is that you can use pretty much anything to set it. Do you want your code to run until you say stop? Use a while loop. Do you want to have the user do something a finite number of times? Use a while loop.
For our program, we’ll be using a while loop. But I will also show you a “for” loop so that you know what it is for the future.
The For Loop
Like the while loop, the for loop uses the keyword “for”. However we’re going to need a bit more than that to use it. The for loop creates or reassigns a variable that will keep track of how many times the loop has looped. Then we have to give the for loop a specific range in which to loop. We can do this with the range function, but in the future we’ll be using something called an array for the for loop.
- for x in range(min, max+1):
- do this
Notice how in the range function, the max number in the range function actually doesn’t count. If the numbers were (1,5), the range it would generate would be 1 – 4.
Alright, now that we know how to use loops, we can start on our game. This post is getting a little long though, so I’ll do a post on Wednesday dedicated to the project. Before that, please go and check out the post on if statements and the post on if statements here and leave a comment if there is anything that isn’t totally clear. I’ll see you guys in the next one.