The while Loop
This is a free course. Log in to run the code exercises and track your progress.
The while Loop
A while loop repeats its block as long as a condition is True. Use it when you do not know in advance how many times to repeat.
n = 1234
digits = 0
while n > 0:
n = n // 10 # remove the last digit
digits += 1
print(digits) # 4
Something inside the loop must change the condition, here n gets smaller each time. If nothing changes it, the condition stays True forever and the program never stops: an infinite loop.
Two tricks with // and % are used again and again with whole numbers: n % 10 is the last digit of n, and n // 10 is n without its last digit.
Read a positive whole number and print the sum of its digits using a while loop.
n = int(input())
total = 0
while n > 0:
# add the last digit to total, then remove it from n
n = 0
print(total)Log in to edit and run this code.