There are three such statements used for special purposes which is standard control statements can’t perform effectively.
Each statement has its own features and will be very useful to control your program execution. It gives you flexibility to re-route program execution to achieve the desired result or build a more generic and powerful solution.
Follow each statement carefully to understand its features.
Sometimes you are in a situation where you want to skip a part of loop (in WHILE or FOR – loop) from execution and continue with the next iteration. You can use break or continue statements to handle such situations.
You are now already known to FOR loop- range control statement hence we will take the same example to demonstrate break statement.
Read more about for-loop
Example 1: We will try to break the for-loop as soon as your program reach to count 5 in a range value of 0 to 10 and print the values to understand execution better.
Example 2: We will try to break the for-loop as soon as your program reach found the character “t” in a string(word) – “P-y-t-h-o-n” and print the characters to understand execution flow better.
The continue statement in python allows you to skip further statements for that specific iteration and send control back to top, beginning of loop.
It can be used in the WHILE or FOR loops.
Let’s modify above examples by just replacing break keyword with continue keyword and see the result.
The output of example 1 with continue keyword – It will print all the range values (0 to 10) except 5.
The output of example 2 with continue keyword – It will print all the characters (P-y-t-h-o-n) except “t”
The pass command in python used where you don’t want to execute any piece of code in the loop. It allows you to skip the block of code from execution.
It is mostly used in the development phase of your program as you may specify pass statement where you feel possibilities that code execution can go in the flow and you want to nullify the block.
Of course, you can track all your pass statements by adding print statement under pass block with appropriate comment.
Let’s discuss same examples –
Example 1: If you want to pass the block of code when counter or range value reach at 5 and everything else should print as-is.
Example 2: If you want to pass the block of code when character “t” found in the string (word) “P-y-t-h-o-n” and everything else should be printed as-is.