while condition: keeps running the block as long as the condition is true. Use it when you do not know in advance how many times to loop: keep dividing until the number is gone, keep asking until the answer is right. Something inside the block must change the condition, or the loop never ends (the lesson runner will stop it after a few seconds and tell you).
A common shape is a counter: set it before the loop, test it in the condition, change it in the body. n //= 10 is the shorthand for n = n // 10.
n = 1
steps = 0
while n < 100:
n *= 2
steps += 1
print(n, steps) # 128 7Your task
Write digits(n) that returns how many digits a non-negative whole number has by repeatedly floor-dividing by 10 (digits(0) is 1), and collatz_steps(n): while n is not 1, replace it with n / 2 when even or 3n + 1 when odd, and return how many steps it took.
Hint 1
For digits: count = 0; while n > 0: n //= 10; count += 1. Handle 0 before the loop.
Hint 2
Collatz: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1, then steps += 1.
Show the solution
def digits(n):
if n == 0:
return 1
count = 0
while n > 0:
n //= 10
count += 1
return count
def collatz_steps(n):
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
return steps