The break statement is used to terminate a loop and then run the statements outside the loop
for i in range(10):#same as range(0,10) print(i) if i == 4: break #breaking the loop when i = 4 print("The loop has been terminated")
0 1 2 3 4 The loop has been terminated
As you can see, the program terminates the loop once i is equal to 4. Let's look at another example.
#Q: Let the user enter a number and if it is negative, exit the loop while True: #while true is used to run the code infinitely, since the condition is always satisfied num = int(input("Enter a number here: ")) if num < 0: break print("Error: Negative number entered.")
Enter a number here: 10 Enter a number here: 12 Enter a number here: 13 Enter a number here: -54 Error: Negative number entered.
We see that the program accepts all positive numbers, but when we enter a negative number, the loop is terminated
The continue statement is used to skip the statements below it for only a fixed number of iterations. After the continue statement, the next iteration begins, ignoring everything after the continue statement.
#Q: Print all the numbers from 1 to 5 except for 4 num = 0 while num<5: num=num+1 if num == 4: print("4 has been skipped") continue else: print(num)
1 2 3 4 has been skipped 5
Break is used to terminate the entire loop while continue is used to skip certain iterations of the loop. Break is generally used to exit an infinite loop while continue is for skipping iterations of a finite loop. Make sure you are clear while writing your program as you may confuse the two statements.