2.6 - Loop keywords
There are two Python keywords that can be used in loops - break
and continue
.
Break
The break
keyword exits the loop entirely. The looping code will stop and the following code after the loop will run.
while True:
text = input("Type exit to finish the loop")
if text == "exit":
break # exit out of the loop
print("The loop finished")
Continue
The continue
keyword moves onto the next iteration of the loop. The looping code will stop and run the next part of the loop as if the first iteration was over.
for i in range(10):
if i == 5:
continue # skip 5
print(i)
Multiple loops
The break
and continue
keywords only perform the action on the innermost loop.
while True:
print("Loop 1")
while True:
print("Loop 2")
break # breaks out of loop 2, but loop 1 will continue
There was meant to be an ad here. Support us by turning off your ad blocker or donating.