### 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 $lo{g}_{10}n$$log_{10} n$ (reminder: $lo{g}_{10}n$$log_{10} n$ is the number $k$$k$ such that ${10}^{k}=n$$10^k = n$. For example, $lo{g}_{10}1000=3$$log_{10} 1000 = 3$ because ${10}^{3}=1000$$10^3 = 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."