In previous lessons, you learned about different types of loops such as for loop, while loop and for-each loop. Each of the loop terminate successfully. What if you want your loop to exit in between execution, or you want to skip some of the iterations.
There are three keywords in python programming that does that for you. In this article, we will learn how to use them in python programs.
Here is the list of keywords that break the normal execution of loop.
- continue
- break
- pass
Continue
The continue
keyword is used inside the loop control structure and based on the conditions it will skip the current execution and continue with the rest of the iterations.
Here is an example of continue
.
# example program for continue keyword in python for i in range(10): if i == 5: continue print(i, end = " ")
The above program prints 10 numbers from 0 to 9 and if the number is equal to 5. it skip the iteration and continue with the rest of the code. The output of the program is given below.
====== RESTART: C:/Python_projects/Loops/Continue_Keyword.py ====== 0 1 2 3 4 6 7 8 9 >>>
You note that the value 5 is not printed, that is because it was skipped.
Break
The break
keyword is known in many programming languages. It break the loop and comes of it as soon as a break
is encountered. However, all iterations are successful until a break is reached.
Consider the following example
for i in range(8): if i > 4: break print(i, end = " ") print("Rest of the code")
In the program above, when the variable i reach 5, the loop is terminated immediately. The rest of the program code is executed successfully.
======= RESTART: C:/Python_projects/Loops/break_keyword.py ======= 0 1 2 3 4 Rest of the code >>>
Pass
Sometimes program wants to create a loop for testing purpose and do nothing. Python will not allow a loop to exist if it does not have at least one indented line of code.
For example
for i in range(10): # No indented code
The above code does not do anything because there is not indented line of code. Pythons produce an error in such cases. See the error below.
You can fix this problem using the pass
keyword. The loop will exist and do nothing with the help of pass.
for i in range(10): pass
Summary
There are fewer programs that require to implement the continue, break, or pass keywords. We have seen that the most frequently used keyword is break. In some program, it is necessary to break out of look structure immediately, and break is certainly the best option.