10.2. Introducing the While Loop

Recall that a for loop is designed to repeat steps for every value in a list. The range function in the code below is designed to generate a list that looks like [0, 1, 2, 3, 4] and thus causes the loop to repeat 5 times. By forcing us to provide that list of values, the for loop requires us to specify the number of iterations there will be before we begin looping.

for iteration in range(5):
    guess = 1/2 * ((number / guess) + guess)

However, there is another way to repeat statements: the while loop. It will repeat the body of the loop as long as some logical expression is true. Just like with a for loop, the body of a while loop is the lines of code after while that are indented. A logical expression is one that is either true or false like x < 5. (We will talk more about them later.)

While loops are typically used when you don’t know how many times to execute the loop. they allow us to say “keep repeating this while we don’t have an answer”. One reason we might not know in advance how many times to repeat is if we are getting input from outside the program. The code below will keep asking you to enter numbers. It will do so until you enter a number that isn’t negative. It will print out the sum and average of all of the numbers you have entered.

The loop in this sample takes your input, which is stored in value as a string like “12”, and turns that into an integer like 12. It checks to see if that value is greater than 0. If so, it does the loop body, if not, we skip over the loop body and continue with the rest of the program.

You have attempted of activities on this page