What are the Control Statements in Python?

In Python, Loops are used to iterate repeatedly over a block of code. In order to change the way a loop is executed from its usual behavior, control statements are used. Control statements are used to control the flow of the execution of the loop based on a condition. There are many types of control statements in Python and in this tutorial, we will discuss all of them.

Control Statements in Python

Break statement

The break statement in Python is used to terminate or abandon the loop containing the statement and brings the control out of the loop. It is used with both the while and the for loops, especially with nested loops (loop within a loop) to quit the loop. It terminates the inner loop and control shifts to the statement in the outer loop.

Input:

age = “\n Please enter your age: ”
while True:
       age = input
       if age >= 18:
              break
       else:
             print (“You’re not eligible to vote”)

Output:

Please enter your age: 17 You’re not eligible to vote
Please enter your age: 18

In the above example, if the age entered is equal to or more than 18, it breaks out of the loop.

Continue statement

When a program encounters a continue statement in Python, it skips the execution of the current iteration when the condition is met and lets the loop continue to move to the next iteration. It is used to continue running the program even after the program encounters a break during execution.

Input:

for letter in 'Flexi ple': 
if letter == ' ': 
        continue 
    print ('Letters: ', letter)

Output:

Letters: F
Letters: l
Letters: e
Letters: x
Letters: i
Letters: p
Letters: l
Letters: e

In this example, the program will skip the space ‘ ‘ in the word and continue with the rest of the iteration.

Pass statement

The pass statement is a null operator and is used when the programmer wants to do nothing when the condition is satisfied. This control statement in Python does not terminate or skip the execution, it simply passes to the next iteration.

A loop cannot be left empty otherwise the interpreter will throw an error and to avoid this, a programmer can use the pass statement.

Input:

for letter in 'Flexiple': 
if letter == 'x': 
        pass 
    print ('Letters: ', letter)

Output:

Letters: F
Letters: l
Letters: e
Letters: x
Letters: i
Letters: p
Letters: l
Letters: e

As you can see in the above example, even though the condition was met, the pass statement didn’t do anything and execution moved to the next iteration.

Closing Thoughts

In this tutorial, we read about the different types of control statements in Python - break, continue and pass. Different control statements have different functions and can be used according to the need in the program. One can read about other Python concepts here.