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