Understanding break and continue Statements in Python
The break statement is used to exit a loop prematurely. When a break statement is encountered, the loop stops executing, and the program control jumps to the first statement following the loop.
for number in range(10):
if number == 5:
break # Exit the loop when number is 5
print(number)
# Output: 0, 1, 2, 3, 4
In this example, the loop will print numbers from 0 to 4. When the loop reaches 5, the break statement is executed, and the loop terminates.
The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. When a continue statement is encountered, the rest of the code inside the loop for the current iteration is skipped.
for number in range(10):
if number % 2 == 0:
continue # Skip the even numbers
print(number)
# Output: 1, 3, 5, 7, 9
In this example, the loop iterates through numbers from 0 to 9 but skips printing the even numbers. When an even number is encountered, the continue statement is executed, and the loop moves to the next iteration.