The while loop
Repeat while the condition holds; break and continue.
while repeats a block as long as the condition is true. The condition is checked before every pass:
n = 3
while n > 0:
print(n)
n -= 1
print("Go!")
Something inside the loop has to change the condition, otherwise the loop never ends. A forgotten n -= 1 is the most common reason a program hangs. In the sandbox such a program is stopped by the time limit.
break leaves the loop immediately, and continue skips the rest of the pass and goes on to the next check. The pattern "repeat until we get what we need" looks like this:
while True:
answer = input("Continue? (yes/no) ")
if answer in ("yes", "no"):
break
print("Please answer yes or no")
while is good when you do not know in advance how many repetitions there will be. For example, when taking a number apart into digits: n % 10 gives the last digit and n //= 10 drops it. The loop runs until the number becomes zero. When you need to go through a ready set of values, or exactly N times, the for loop from the next lesson is more convenient.
Practice
Countdown
What does the program print? Write the output on one line, separated by spaces.
n = 3 while n > 0: print(n, end=" ") n -= 1An endless loop
Which loop never ends?
- i = 0; while i < 3: i += 1
- i = 0; while i < 3: print(i)
- while True: break
- i = 5; while i > 0: i -= 2
Sum of digits
Write a function digit_sum(n) that returns the sum of the digits of a non-negative integer. Solve it with while, % and //, without turning the number into a string.