The While Loop

We have already learned about the for loop and now it is time to learn about the while loop. The while loop is like a combination of the for loop and the if function. The while loop looks like the following:

—-Do Something

The While Loop will run as long as the Boolean in it’s brackets is true. A cool implementation of this is an infinite loop. Try the following code:


If you don’t have python, use this python executor. Once your satisfied, In python click control + C (command + c on a mac) or press the stop button on the online executor to stop running the code. This code would run forever if you let it. This loop has many applications. Suppose you are making a game with health you could run:

—-Game Code
print(“You died”)

Try implementing this in the challenge you did last lesson. Instead of using a for loop to determine the number of turns, try using a while loop that runs until the player’s health is less than zero

Try it Yourself

Try implementing a for loop using a while loop. Initiate i at 0 using:

i = 0

You can also initialize i at another number (if you wanted to loop from 4 to 60 instead of 0 to 60 for example). Next set max_num equal to whatever number you like. It should look similar to this:

max_num = 10

Than repeat this as long as i is less than max_num. Don’t forget to increment i by one each time! you can do this using:

i = i+1

To shorten this, the creators made a special command which does the same thing:

i += 1

It’s worth noting that the number at the end doesn’t need to be one, it could be any number. If I wanted to increment by 4, I could use:

i += 4

Try implementing this loop yourself below. Bonus: Create a variable step and make i increase by that amount:

One thought on “The While Loop

Leave a Reply

Your email address will not be published. Required fields are marked *