Counting with while
count = 5 while count > 0: print(count) count -= 1 print("Done")
Write Python. Understand every error.
Python basics · topic 10 of 25
A while loop repeats as long as its condition stays true. Use it when you do not know in advance how many rounds you need.
count = 1 while count <= 3: print(count) count += 1
Something inside the loop must change the condition, otherwise the loop never ends. In this app, a program that runs longer than 3 seconds is stopped and explained.
break leaves the loop immediately. continue skips the rest of the current round and moves on to the next.
A classic while pattern takes a number apart digit by digit: n % 10 gives the last digit and n // 10 removes it.
n = 472 while n > 0: print(n % 10) n = n // 10
while loop repeats as long as its condition is true, so something inside the loop must change the condition.break leaves the loop immediately. continue skips to the next round.while when you do not know in advance how many rounds are needed, and for when you do.n % 10 gives the last digit of a number and n // 10 removes it.continue before the line that changes the counter, so the change never happens.
count = 5 while count > 0: print(count) count -= 1 print("Done")
n = 2026 while n > 0: print("digit:", n % 10) n = n // 10
for n in range(1, 100): if n * n > 50: print("First square above 50 is", n * n) break
for n in range(1, 11): if n % 3 == 0: continue print(n)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
n = 1 while n < 20: n = n * 2 print(n)
n goes 1, 2, 4, 8, 16, 32. The loop stops when n is 32, which is not less than 20.
for i in range(10): if i == 4: break print(i, end=" ")
break leaves the loop completely when i reaches 4.
for i in range(6): if i % 2 == 0: continue print(i, end=" ")
continue skips the rest of the loop body for even numbers.
The loop runs forever unless something inside it changes the condition or uses break. Py-CRAFT stops it after a few seconds.
count = 0 while count < 3: count += 1 print(count)
count goes 1, 2, 3. When count is 3, the condition count < 3 is False.