While loopsΒΆ

Here is the syntax for while-loops:

while <cond>:
     <block>

This means: repeat <block> while the condition <cond> is True. Stop repeating <block> once the condition <cond> becomes False.

Let's write the function my_log10(n) which computes log10n (reminder: log10n is the number k such that 10k=n. For example, log101000=3 because 103=1000.

In [1]:
def my_log10(n):
    res = 1
    i = 0  #a counter for the number of times the while-loop runs
    while res < n:
       res = res * 10
       i = i + 1
    
    return i

Here is the idea: res is multiplied by 10 every time we enter the while loop, and the loop terminates when i is no longer smaller than n. The counter variable i is incremented by 1 every iteration, so when the loop has terminated, counter contains the number iterations required to make i larger than 2 if we double i at every iteration.

Note: one execution of the block is called an "iteration."