Break and continue statements
Break and Continue Statements A break statement is used when you want to exit a loop or nested structure. It is similar to a "return" statement, but it...
Break and Continue Statements A break statement is used when you want to exit a loop or nested structure. It is similar to a "return" statement, but it...
Break and Continue Statements
A break statement is used when you want to exit a loop or nested structure. It is similar to a "return" statement, but it is used to exit the current iteration of the loop. This allows you to control the flow of your program and execute other code or instructions.
Example:
python
for i in range(5):
for j in range(3):
print(i, j)
print("Finished iteration %d" % i) # This code will only print the first three iterations
In this example, the inner for loop will iterate 3 times. The outer for loop will iterate 5 times. When the inner loop completes, the program will print the values of i and j. The program will then print the string "Finished iteration %d" % i, where i is the current value of the outer loop.
After the inner loop completes, the program will move on to the next iteration of the outer loop. This allows you to control the flow of your program and execute other code or instructions as needed.
Continue is used to skip the remaining code in a loop iteration. It is similar to a "continue" statement, but it is used to skip the next iteration of the loop. This allows you to control the flow of your program and execute different code or instructions in each iteration.
Example:
python
for i in range(5):
for j in range(3):
if j == 2:
continue
print(i, j)
print("Finished iteration %d" % i) # This code will only print the first two iterations
In this example, the inner for loop will iterate 3 times. The outer for loop will iterate 5 times. When the inner loop reaches the value of 2, the continue statement will skip the remaining code in the loop iteration. This allows the program to print only the first two iterations of the outer loop.
Summary:
Break statement exits a loop when the current iteration is completed.
Continue statement skips the remaining code in a loop iteration