Python Basics: Understanding The Flow Control Statements

img1.jpg

Introduction

In this article we will learn about control statements that are available in Python language. It is very important to control the programe execution because in real scenarios the situations are full of conditions and if you want your program to mimic the real world closer then you need to transform those real world situations into your program . For this you need to control the execution of your program statements. This article is all about controlling the program execution sequence. It is commonly known as  control flow in programming terms. So let's dive in the river of program statements that is controlled by python control flow tools.

Understanding the control flow

As the article is focusing on control flow tools , it is must for us to understand these terms before we use them. The first word is control that simply means controlling. We don't want the default behavior, we want different one. We are getting the different behavior by controlling some aspects of the behavior. Now it comes to flow, Flow is just a way or sequence of program execution. By default every statement of program is executed one by one in an order they appear in a program code. When we combine the above two words we get control flow, That simply means controlling the flow of program execution to get desire behavior or result. Using control flow we are controlling the statement execution, Now program will no longer be executing in sequence, the execution is controlled by control tools. To understand it let's take few examples, In a bank management program we don't want to allow the retrieve function to work if the money in an account is zero. In that case we need to skip the retrieve program code and that is control flow.


img2.jpg


Control flow tools in python

Python provide various tools for flow control. Some of them are if , if .. elif .. else, if..else,while ,for , switch, pass, range, break, else, continue, function etc. In this article I'll be covering only if-else and loops.

If - If this is the case then do this

This control statement indicate that if something happens then do this . It's a good way of handling some short conditions. An if block can be followed by zero or any number of else block.

if (condition):                    

    statements...


img3.jpg


Note: Use of colon ( ":" ) in python is same as we use brackets in java or c++. Python uses colon and indentation for defining the scope or code block. So if you are getting an error like the following picture then correct your code indentation.


img5.jpg


If ... else

It's like if have money then spend else wait for salary. I hope it's clear from the previous line what this statement means. It's like if the conditions of if block is evaluated to true then execute that block else execute the else block. The else block is optional and one if can have any number of else blocks.

Syntax:

if (condition):                    

    statements...

else:

    default statements...


img4.jpg


If ... elif ... else

It's like checking multiple conditions. Let's Take an example if pocketMoney greater then 90T then Okay else if pocket money is equal to 50T and Less then 90T then its average else it's not enough. Basically that statement can replace switch statement. You can put any number of elif blocks after if and else block is optional.

Syntax:

if (option1 condition):                    

    option1 statements...

elif(option2 condition):            

    option2 statements...

elif(option3 condition):          

    option3 statements...

else:

    default option statements...


img6.jpg


For statement

It is used for looping over a sequence. Python doesn't supports old for loop or c-style for loop. In traditional style for loop we have one variable which iterates over a sequence and we can change the value of sequence and variable as well but in modern for loop we have iteration variable that iterates over a fixed sequence. We can not change the sequence as well as iteration variable during iteration. 

Syntax:

 

for iterator_name in iterating_sequence:

    ...statements...


img7.jpg


If you want to modify the sequence then we need to create the copy of the original sequence before doing this.


img8.jpg


Using range

Sometimes it is required that we just want to iterate over number sequence like 1,2,3,4,...  To solve this purpose python provides range function which generate the arithmetic progression with number of terms equal to the parameter passed in it. We have 3 variations of range() function. One take only

Syntax:

1. for iterator_name in range(10):

    ...statements...              

 

2. for iterator_name in range(start,end):

    ...statements...
              

3. for iterator_name in range(start,stop,increment):

    ...statements...              


img9.jpg


Else, Break, Continue in For loop

Break is used for terminating the loop abnormally. i.e that even the sequence is not completed but loop is exited.

Continue is used for continuing to next iteration of loop without doing anything inside the loop.

Else is introduced in python and it is placed in loop without if. It will execute only if the loop is terminated without break.

Note: there are two more else statement, one is for if that I already explained and other is with try. The difference between try else block and loop else is try else block executes when no code is executed and loop else executes when no break is executed. 


img10.jpg


Pass statement

Pass statement is used when you don't want to do anything but it is required for the sake of syntactical correctness. Pass has two common uses.

  1. It is used for creating minimal classes.
  2. It is used as place holder. For example consider the following snippet


    img11.jpg 

Example

politicleParties=['AAP','Elephent','Hand','Rest']

electionYear=["2014","2009","2005","2001"]

countryStatus=["worst","developing","developed"]

corruptionStatus=["Max","Normal","Min"]

for party in politicleParties:

    year=input()

    if year in electionYear:

        if year == "2014":

            print("AAp Wins!")

            print("Country status: "+countryStatus[2])

            print("Corruption Status: "+corruptionStatus[2])

            break

        elif year == "2009":

            print("Hand Won :(")

            print("Country status: "+countryStatus[0])

            print("Corruption Status: "+corruptionStatus[0])

            continue

        elif year == "2005":

            print("Hand won!")

            print("Country status: "+countryStatus[0])

            print("Corruption Status: "+corruptionStatus[0])

        elif year == "2001":

            print("Rest Won!")

    else:

        print("Wrong year of election!")

else:

    print("The above loop was just for demonstration purpose!")



img12.JPG


Summary

It's time to clean the board. We have reached the end of the article and it's time to check what we have learned from this. The best way to do that is to just practice what we have learned. If you want, you can create a program for printing the prime numbers between 1 and 100. If you have completed that program then that means you undestand the flow control.

Thanks for reading and don't forget to share and comment.

Up Next
    Ebook Download
    View all
    Learn
    View all