Looping and Looping and Looping

In Python, there are two different types of loops: while(): loops, and for(): loops. Today, we are only going to be using a while loop, and we will introduce the for loops later on. A while() loop will repeat the same chunk of code over and over again, as long as whatever we put inside of the parenthesis stays true. The fact that they are so simple makes the extremely flexible.

A while loop is pretty simplistic, all that you need to make one is the keyword while, and some condition. For example, the code on the right will run over and over forever, because “40 > 1” will never not be true.

while(40 > 1):
    print("Still running!")

The loop we just coded will run as long as 40 is greater than 1. In other words, this will run forever. If we want this loop to eventually stop, we’re going to have to change the condition so that it can eventually come to a stop. One way to do so is to make the condition based around a variable, that will change as the loop runs. For example:

count = 99
while (count > 0):
    count = count - 1 

Coding these four lines will make a loop that will run for as long as the variable count is greater than 0. Because we are subtracting one from our variable every time we run through the loop, it will eventually stop running when count = 0. Give this a try in your code editor!