In the previous tutorial, We already learned that a loop is used to iterate a set of statements repeatedly as long as the loop condition is satisfied. In this article, we will learn to use break & continue in python to alter the flow of a loop. Break is used to exit a for loop or a while loop, whereas Continue is used to skip the current block, and return to the “for” or “while” statement. A break or continue statement found within nested loops applies to the nearest enclosing loop.
EXAMPLE 01 : Write a program to print natural number from 1 to 10 and stop when number reaches 5.
>>> a = 1 >>> while (a<=10): if (a==5): break print (a) a=a+1 Output: 1 2 3 4
In this example, we are printing the first ten natural numbers. In each iteration the value of a increases by 1. During fifth iterations it reaches five. It checks the condition if a is equal to five. When it satisfies the condition, the break statement is executed and the flow of execution jumps out of execution of the while loop.
Break & continue in python is used along with if statements. If we do not use it with an ‘if’ statement then the break statement will be encountered in the first iteration of loop and the loop would always terminate on the first iteration.
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.
EXAMPLE 02: Write a program to print numbers from one to ten and skip number 5
>>> a = 1 >>> while (a<=10): if (a==5): a=a+1 print("number 5 is skipped") continue print (a) a=a+1 Output: 1 2 3 4 number 5 is skipped 6 7 8 9 10
We are skipping the print(a) statement inside the loop by using a continue statement when the number is equal to 5, this way all number 5 is skipped and the print statement executed for all the other numbers.
Pass in python is a NULL statement which is used when we have no codes to execute. Suppose, we declare a loop and we have no code to execute but we may have something in future. Then in this case we use a pass statement.
EXAMPLE 03 : Write a program to print first 5 odd number
>>> a = 1 >>> while (a<10): if (a%2==0): pass else: print (a) a=a+2 Output: 1 3 5 7 9
In the above example, when the number is even we are doing nothing. If it is odd then we are displaying the number.
This page is contributed by Diwas & Sunil . If you like AIHUB and would like to contribute, you can also write an article & mail your article to firstname.lastname@example.org . See your articles appearing on AI HUB platform and help other AI Enthusiast.