Python Basics: Understanding The Flow Control Statements

img1.jpg

Introduction

 
In this article, we will learn about control statements that are available in the Python language. It is very important to control the program 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 into the river of program statements that are controlled by python control flow tools.
 
Understanding the control flow
 
As the article is focusing on control flow tools, it is a 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 a different one. We are getting 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 the 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 the program will no longer be executing in sequence, the execution is controlled by control tools. To understand it let's take a 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 provides 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 indicates 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 the 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 you have money then spend else wait for your salary. I hope it's clear from the previous line what this statement means. It's like if the conditions of if block are evaluated to true then execute that block else execute the else block. The else block is optional and one if you 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 it's average else it's not enough. Basically that statement can replace a 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 support old for loop or c-style for a 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 the 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 a 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 generates the arithmetic progression with a number of terms equal to the parameter passed in it. We have 3 variations of range() function. 
 
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 the loop is exited.
 
Continue is used for continuing to next iteration of the loop without doing anything inside the loop.
 
Else is introduced in python and it is placed in the loop without if. It will execute only if the loop is terminated without break.
 
Note: there are two more else statements, one is for if that I already explained and the 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 a place holder. For example, consider the following snippet
     
    img11.jpg
     
Example
  1. politicleParties=['AAP','Elephent','Hand','Rest']  
  2. electionYear=["2014","2009","2005","2001"]  
  3. countryStatus=["worst","developing","developed"]  
  4. corruptionStatus=["Max","Normal","Min"]  
  5. for party in politicleParties:  
  6.     year=input()  
  7.     if year in electionYear:  
  8.         if year == "2014":  
  9.             print("AAp Wins!")  
  10.             print("Country status: "+countryStatus[2])  
  11.             print("Corruption Status: "+corruptionStatus[2])  
  12.             break  
  13.         elif year == "2009":  
  14.             print("Hand Won :(")  
  15.             print("Country status: "+countryStatus[0])  
  16.             print("Corruption Status: "+corruptionStatus[0])  
  17.             continue  
  18.         elif year == "2005":  
  19.             print("Hand won!")  
  20.             print("Country status: "+countryStatus[0])  
  21.             print("Corruption Status: "+corruptionStatus[0])  
  22.         elif year == "2001":  
  23.             print("Rest Won!")  
  24.     else:  
  25.         print("Wrong year of election!")  
  26. else:  
  27.     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 understand the flow control.
 
Thanks for reading and don't forget to share and comment.


Similar Articles