Using loops in Python automates and repeats tasks efficiently. But sometimes a condition may arise where you want to exit the loop completely, skip the iteration, or ignore this condition. This can be done with loop control statements . Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects created in that scope are destroyed. Python supports the following control statements.
break statement is used to end a loop or statement in which it is present. The control will then jump to the statements after the break statement, if available. If a break statement is present in a nested loop, it terminates only those loops that contain a
Consider the situation when you want to iterate over a string and print all characters until you meet the letter “e” or “s”. It is stated that you must do this with a loop, and only one loop is allowed.
This is where the
break statement is used. What we can do is iterate over the lines, using either a
while loop or a
for loop and every time we have to compare the iterator value with “e” or “s”. If it`s & # 39; e & # 39; or & # 39; s & # 39;, we will use a break statement to break out of the loop.
Below is the implementation.
ge Out of for loop ge Out of while loop pre>
Continueis also a loop control statement, just like a break statement. The
continuestatement is the opposite of the break statement, instead of terminating the loop, it forces the next iteration of the loop to run.
As the name suggests, the continue statement causes the loop to continue or to perform the next iteration. When the continue statement is executed in a loop, the code within the loop following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax :continue pre>
Consider the situation, when you need to write a program that prints a number between 1 and 10, not 6. It is specified that you should do this with a loop, and only one loop is allowed.
This is where the
continuestatement is used. Here we can start a loop from 1 to 10, and every time we need to compare the value of the iterator with 6. If it is 6, we will use the continue statement to go to the next iteration, without printing anything else, we will print the value. P >
Below is the implementation of the above idea:
1 2 3 4 5 7 8 9 10
As the name suggests, the pass statement simply does nothing. The pass statement in Python is used when a statement is required syntactically, but you don`t want any command or code to run. It is like a
null operation, since nothing happens if it is done. The
Pass operator can also be used to write empty loops. Pass is also used for empty control statement, function and classes.
gee Pass executed ks
In the above example, when the value of i becomes "k", the pass statement did nothing and hence the letter "k" is also printed.