The break and continue keywords, or similar, are found in most programming languages.
- break causes a loop to immediately stop executing.
- continue skips any code that’s found after the continue keyword in the loop body and goes straight to the next loop iteration.
Break Example
Note that you can use while True to create an “infinite loop”. You can then use break to stop the loop at the desired point.
value = 0
while True:
value += 1
if value > 3:
break
print("Hello", value)
print("Program finished")
Hello 1
Hello 2
Hello 3
Program finished
Continue Example
for i in range(5):
if i == 3:
continue
print("Loop counter:", i)
print("Program finished")
Loop counter: 0
Loop counter: 1
Loop counter: 2
Loop counter: 4
Program finished
Leave a Reply