Class Notes: While loops

while <condition>:
    <steps>

The condition is any expression that can be true or false (i.e. expressions that evaluate to a boolean). This is the same as you use on if and elif.

The way while loops work is:

  1. Check the condition

    a. If it is true: run the steps, go back to 1

    b. If it is false: go to the first line after the loop (starting at the same column as while)

Note: If the condition is always true, your program will run forever! This is what is called an infinite loop.

Typically the loop condition will use a variable that is modified inside the loop, for example:

It turns out that some problems can be solved with a for loop or a while loop. We can convert the standard for loop into a while loop as shown below.

In fact, some people call for loops syntactic sugar since the functionality of a for loop can be achieved with a while loop

If while loops and for loops are very similar, which one is more powerful? It depends on the programming language. In some programming languages, for loops, and while loops are even closer, making them equivalent.

It is essential to master both and learn how and when to use each. Sometimes, a for loop can be more appropriate and human-readable. In other cases, a while loop is the best method.

How to pick between a for loop and a while loop?

The rule of thumb is the following. Use a while loop when you do not know how many times you need to repeat a sequence of steps, but you know you should repeat while some condition is True (or until a condition becomes False).

Important things to keep in mind when using while loops

Be careful about how the variable is changed.

What's the output of the following function for n = 5?

There's no output. The function never terminates. This is called an infinite loop.

Understand the "Flow of execution"

What's the output of the following function for n = 8?

Even if the condition $i < n$ becomes False before the last increment of $x$, Python will complete the iteration before checking again the condition

You can return inside a while loop

What does this function do?

Similar to for-loops, if the program flow hits a return in the middle of an iteration, it simply returns and does not run more iterations.

The code below, in particular, only runs the first iteration, and then stops.

Exercise 1

Implement the function numberOfDigits(n) that returns the number n. For example numberOfDigits(15110) should return 5.

Exercise 2

Implement the function countOneDigits(n) that returns the number of digits of n equal to 1. For example, countOneDigits(15110) should return 3 (there are three ones in 15110).