Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
while Loops
A for loop runs once per item. A while loop runs as long as a condition stays true, which is what you want when you do not know in advance how many steps it will take.
n = 100
steps = 0
while n > 1:
n = n / 2
steps += 1The thing that makes a while loop different from a for loop is also its main danger: something inside the body has to make the condition eventually false. If n never shrinks, the loop never ends, and in this sandbox that shows up as a timeout rather than a hung browser.
Every while loop you write should have an answer to "which line makes this stop?". In the example above it is n = n / 2.
Your task:
Write halvings_until_below(value, limit) that repeatedly halves value and returns how many halvings it took to get strictly below limit.
halvings_until_below(100, 10) returns 4, because 100 goes to 50, 25, 12.5, 6.25, and 6.25 is the first value below 10.
If value is already below limit, return 0.
Example Tests
100 halved four times first drops below 10
Input: {"limit":10,"value":100}
Expected: 4
Already below the limit needs no halvings
Input: {"limit":10,"value":5}
Expected: 0
Exactly at the limit still needs one halving, since below is strict
Input: {"limit":10,"value":10}
Expected: 1
def halvings_until_below(value, limit):
"""
Count how many times you must halve value to get below limit.
Args:
value: a positive number
limit: a positive number
Returns:
The number of halvings needed. 0 if value is already below limit.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests