Control Statements

Control statements are used to control the execution flow. The control statements that are available in python are: break, continue and pass.

Break

The break statement can stop a loop without meeting the loop requirements defined. With the break statement, it is possible to abort the loop. 

# looping statement
break;

In python, the syntax of break statement is the following:

Let’s see the house example:

count = 100
while (True):
    if (money < 500):
        count = count + 100
        print("Count ...")
        print("Count--> " + str(count))
    else:
        print("Count stopped")
        break

 

Output:
'Count ...
Count --> 200
Count ...
Count --> 300
Count ...
Count --> 400
Count ...
Count --> 500
Count stopped


Let’s see another example with a for loop:

for number in range(0,11):
    print(number)
    if (number == 5):
        break

 

Output:
0
1
2
3
4
5


We do a for loop range between 0 and 10. If the number in the for loop is equal to 5, then the for loop is ended.

Continue

Now continue is another control statement, which allows you to jump over to the beginning of the loop, in other words, it skips the remaining lines of code and starts the loop over again. In Python, the syntax for the Continue statement is the following:

# loop goes here
continue
# the following code is skipped

But how can I apply this control statement? The response is simple. Imagine that you want to count to 10 but only want the odd numbers. Let’s take a look at the following example:

for number in range(1,11):
    if ((number % 2) == 0):
        continue
    print(number)

 

Output:
1
3
5
7
9


In the example above, if we want only to print the odd numbers, we can use continue to start the loop again if the number is even.
 

Pass
The last control statement is pass. Pass is null operation, in other words, you are executing an empty code.
The syntax for pass is simple, 

pass

As an example, let’s take a look to a simple example of how pass works:

for number in range(0,10):
    pass
print("Finish code...")

 

Output: Finish code...


In this simple example, the for loop runs without producing any output.
Let’s take a look to another example:

for number in range(0,6):
    if ((number % 2) == 0):
        pass
        print("Passcode in even number")
    else:
        print(number)

 

OutPut:
Passcode in even number
1
Passcode in even number
3
Passcode in even number
5

 

Related Tutorials