In addition to the for
loop, we have a second type of loop, namely, the while
loop.
Unlike for
, where we know the number of repetitions in advance, while
is used when the
loop depends on some condition. The loop body is repeated until the condition is met.
response = input('Say aaa!')
while response != 'aaa':
print('Incorrect, try again')
response = input('Say aaa!')
But pay attention! It is very easy to write a loop with a condition that is always true. This kind of loop will be repeated forever.
from random import randrange
while True:
print('The number is', randrange(10000))
print('(Wait for the computer to get tired…)')
The program can be interrupted with Ctrl+C.
This shortcut will raise an error and the program will end - like after every error.
Finally, we have the break
command, that will signal the process to ‘jump out’ of the loop,
and commands after the loop will be performed immediately.
while True:
response = input('Say aaa!')
if response == 'aaa':
print('Good')
break
print('Incorrect, try again')
print('Yay and it did not even hurt')
The break command can only be used inside a loop (while
or for
),
and if we have nested loops, it will only jump out of the one where it is used.
for i in range(10): # Outer loop
for j in range(10): # Inner loop
print(j * i, end=' ')
if i <= j:
break
print()
Break
will jump out of the inner loop and back to the outer loop
when i is less or equal than j.
Back to while
!
Can you write the following program?