Using break to Stop Loops
The break
keyword immediately terminates a loop and proceeds to execute the code that follows the loop.
It is typically used within a loop when a specific condition is met, and further iteration is unnecessary.
Example of Using the break Statement
Stopping a loop using break
# Print numbers from 1 to 10, but stop the loop at 5
for i in range(1, 11):
# When i equals 5
if i == 5:
# Exit the loop
break
# Print i
print(i)
Output
1
2
3
4
In the code above, the loop for i in range(1, 11):
iterates through numbers from 1 to 10, but when i
equals 5, it encounters break
and the loop terminates.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.