Python programming languages provides break and continue keyword to control a flow of a loop statement. As we know unless there is some error, the loop statement continues to run unless the loop terminating condition is met. Say we have a loop running for long period of time, if we want to stop it in the middle of execution, how would we do that? The answer to this is using break statement.
Break– This keyword helps to exit out of a loop when certain condition is met.
Continue– This is the opposite to break it forces the loop to run the next iteration. If the continue statement is reached it forces the loop to run the next iteration without running the code below it.
The break keyword is used to exit out of the loop.
The following control flowchart diagram will explain the working of break.
for item in range(1, 10, 1): if item == 5: print("inside break statement") break print("item = ", item)
item = 1 item = 2 item = 3 item = 4 inside break statement
In this program loops through item from 1 to 9, but since we have kept break statement as it hits 5, so 5 and other items are not printed and the statement exits out of the loop.
flowchart of continue statement.
for item in range(1, 10 , 1): if item == 5: print('inside continue statement, 5 will not be printed') continue print("item= ", item)
item= 1 item= 2 item= 3 item= 4 inside continue statement, 5 will not be printed item= 6 item= 7 item= 8 item= 9
Here, as soon as we hit 5, we do not go to below statement(i.e. print(“item = “,item)) rather the program starts new iteration from 6 and all other items except 5 are printed.
pass generally means do nothing. It is generally used with a loop or function or class, etc to only make the signature of it so that later we can write some code. When writing code we generally have to think on a higher level before diving into details. We define the signature of the element(function, class, loops, etc) and use pass inside it to skip the error message which python interpreter through when we only define the element name and not its body.
# python pass for first_value in range(1, 10, 1): # implement this later pass for second_value in range(1, 20, 1): # implement this later pass def first_function_name(): # implement this later pass def second_function(): # implement this later pass class FirstClass: # implement this later pass class SecondClass: # implement this later pass
This above code will not generate any output but will only act as a signature. Don’t worry about def and class there are way of defining a function and class respectively. We will see those examples in later chapter.