Skip to main content

Section 2.1 While Loops

A while loop runs "while" something is true. As long as the condition is true, it will keep repeating the code. This can be dangerous though! If the rule is never false, the loop will never end. We must be careful to make sure that our rule will eventually be false.

Subsection 2.1.1 Example of a While Loop

Let’s look at an example of a while loop. In this example, we will start with a variable set to 1, and we will keep doubling it while it is less than 100.
In this code, the value of x is first set to be 1. Then, the while loop checks to see if x is less than 100. Since it is, it multiplies x by 2, and the value of x is 2. Then, the while loop checks again to see if x is less than 100. It is, so it doubles x again, and x is now 4. This continues to where x is 8, 16, 32, 64, and then finally 128. Then, when the while loop checks to see if x is less than 100, it finds that it is not, so it stops. It then prints the value of x, which is 128.

Exercises 2.1.2 Exercises

1.

Write a while loop that starts with a variable set to 3, and keeps adding 3 to it while it is less than 50. Print the final value of the variable.
Solution.
We will use "x" for our variable name. First, we set it equal to 3. Then, a while loop checks if the value is less than 50. If it is, 3 is added to x. Then, outside of the while loop, we print the value of x. This print happens after the while loop is done.
x = 3
while x < 50:   #while x is less than 50
    x = x + 3      #add 3 to the value of x
print(x)