Table of contents
Python Control Statements
While writing a python program, you will encounter many situations when you need to execute a block of statements out of its normal sequence. To do this, control statements are used with loops (for, while) and decision making statements (if…elif…else). Python has three control statements that allow you to break out of normal execution.
Python break Statement
The break statement terminates the current loop and control goes to the next statement outside of the current loop. This is used when you need to stop the execution of a loop when some condition is satisfied. Both for and while loops can have the break statement.
for i in range(0, 5) if i == 3: break print(i)
0 1 2
In the above example, the for loop without if and break statements would have printed 0, 1, 2, 3 and 4 in each line. However, since we included break statement inside the if block, the loop terminates when the condition i == 3 satisfies so only 0, 1 and 2 are printed.
Python continue Statement
While the break statement completely terminates the current loop, the continue statement skips all the statements after it for the current iteration. After the execution of the continue statement, the control goes back to the beginning of the loop. It can be used with both for and while loops.
for i in range(0, 5) if i == 3: continue print(i)
0 1 2 4
In the above example, when i == 3 condition is True, the continue statement is executed. So, the print(i) statement is skipped and the control goes back to the top of the loop.
Python pass Statement
The pass statement in python can be used when we know we need a loop, function or a class but don’t know yet what to write in it, that is to implement stubs. It is a null statement and the interpreter still executes it but nothing happens when it is executed.
for i in range(0, 5) if i == 3: pass print(i)
0 1 3 2 4
In the above example, the pass statement is executed when condition i == 3 is True, however, it doesn’t do anything even though the interpreter executes it.