The while loop
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
while repeats a block of code as long as the condition is true:
n = 3
while n > 0:
print(n)
n -= 1 # without this line the loop would never end
print("Liftoff!")
# 3, 2, 1, Liftoff!
Before each repetition Python checks the condition again. As soon as it becomes false, it leaves the loop.
while is good when you don't know in advance how many repetitions there will be. A classic example is taking a number apart into digits: n % 10 gives the last digit, and n // 10 "cuts it off".
n = 472
while n > 0:
print(n % 10) # 2, then 7, then 4
n //= 10
If a program "hangs", most likely the loop condition never becomes false. On the platform such a program is stopped after 5 seconds.
Task. Read a non-negative whole number and print the sum of its digits. Solve it with while, without turning the number into a string.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.