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 (reminder: is the number such that . For example, because .
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."