Whenever we use any loops in python, try except statements or functions, it expects something to be on the next line. This is the general syntax of statements like these.
for num in numbers: # something must be here
Nothing happens when
pass is executed. Its main purpose is to act as a placeholder where the interpreter expects a statement.
Remember a colon-separated compound statements needs a header and a suite? If you want a suite to do nothing, you cannot end the statement with the colon
:. This is where
pass comes in handy, as a statement is syntactically required.
But why would we want a compound statement to do nothing in the first place?
If there’s a function or a loop that we would like to implement in the future, we might construct an empty function or loop first with an empty body. Since this is syntactically illegal, we use the null statement
pass as a placeholder to comply with the syntax requirement.
This is useful for creating an empty clause in project development.
The break statement allows us to exit a loop without its completion. This comes in handy where you want to find some particular element and did not want to iterate the loop even after finding the element. The break statement can be used to terminate the loop as soon as we find the element.
This is an example for a “for loop” with break statement.
This will print the numbers from 0 to 5 and terminates. The break statement can also be used in a while statement like this.
This is an infinite while loop with a break statement, which does the same job as the previous for loop.
The continue statement will ignore the rest of the statements in a loop after the continue statement. Unlike break it will stop the iteration rather skips a particular iteration.
This will print something like this.
0 1 3 4 5 6 7 8 9
Note that it skips the print statement after meeting the condition “num == 2”.
Learn your basics and code in python. Happy coding!