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.
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...
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.
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...
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...
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...
If you want to modify the sequence then we need to create a copy of the original sequence before doing this.
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):
3. for iterator_name in range(start,stop,increment):
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.
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.
- It is used for creating minimal classes.
- It is used as a place holder. For example, consider the following snippet
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!")
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.