Controlling Logic Flow Inside Loops
In loops, break
and continue
are keywords used to control the execution flow of the loop.
break
immediately terminates the loop, while continue
skips the current iteration and proceeds to the next one.
What is the break Keyword?
The break
keyword is used to immediately exit a loop when a certain condition is met.
For example, the while loop below has a condition count < 10
, but the loop exits when count
is 5.
count = 0
while count < 10:
print(count)
# Increment count by 1
count += 1
# When count equals 5
if count == 5:
# Exit the loop
break
Running this code will stop the loop when count
reaches 5, resulting in the following output:
0
1
2
3
4
What is the continue Keyword?
The continue
keyword immediately ends the current iteration and proceeds to the next iteration of the loop.
count = 0
while count < 5:
# Increment count by 1
count += 1
# When count equals 3
if count == 3:
# Skip to the next iteration
continue
print(count)
When this code is executed, the iteration where count
equals 3 is skipped due to the continue
keyword, producing the following output:
1
2
4
5
As shown above, utilizing the break
and continue
keywords allows you to control the logic flow within loops based on the specific conditions.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.