Control Flow Statements in Python
Video Tutorial
Overview
In this article, we’re going to learn about a very important topic of python programming i.e. flow control in python. You’ll see that almost all basic to advanced level programs are kind of incomplete without having control statements.
So, in other words, if you’re looking to build an application for future generations or just want to start with python then this article would be your stepping stone to achieve your goal.
What is Flow Control in Python?
There are two words, the first is flow and the second is control. Let’s try to understand them and make a relationship out of it.
From a technical perspective, we can say that flow is nothing but many statements consisting of multiple operations which need to be executed. For example, add 2 and 3 is a statement (or expression in this case) where operation is addition. Like this, we can have similar or different kinds of statements according to the problem we’re solving through the code.
Now, we have got the statements that we include in our code. But the thing we’re missing is the control. We don’t have any control over the statements yet. By control, I mean the decision power. To relate this with real life, one can imagine that in their day-to-day life, they make decisions whether to do this or that, choose this or that, etc. And, after deciding we follow the steps to achieve it (in the ideal case of course). Similarly, in the coding world also, we make decisions and according to the situation, we follow required statements and skip irrelevant ones.
Let’s understand the flow control in python through another example. Let’s imagine ‘n’ number of students who have to go to the examination hall to give their paper. But some of them are lazy and for lazy students, there are some special rules.
Special rules:
- No marks deduction if arrived at the examination hall on time.
- If 10 mins late, then 10 marks will be deducted.
- If 30 mins late, then 30 marks will be deducted.
- Zero marks if later than 30 mins.
Let’s understand this example with a diagram and we later discuss this same example with python code (once I introduce you to the type of flow control)
We depicted the same example through a diagram that says that if a student is not lazy, no marks will be deducted (X marks). If a student is 10 mins late then 10 marks will be deducted from the total marks gained (Y marks). Similarly, if it is later than 10 mins and appears under 30 minutes, 30 marks will be deducted from total marks (Z marks). Else, anyone who comes after 30 mins will be allocated zero marks.
Before implementing this example on python, let me just quickly discuss the importance of python flow control.
Importance of Flow Control in Python
It’s very much clear by now why we need python flow control. To decide the flow of your program and make it work exactly how you want it to be, we need flow control. And we use this in our day-to-day life also. Like, before crossing the road we check if we can safely cross the road or not. If not, we wait until safety is assured else we cross. Did you get the hang of it now?
We’re just making decisions and telling how the code should execute in certain situations, which statement to run before or after, etc. We’ve beautiful concise ways to implement flow control in python. Let’s discuss them.
Types of Flow Control in Python
- Conditional
- Loops
Conditional
- if
- if else
- if elif else
Let’s understand them one by one using the exam problem defined above.
For simplicity, the default time is 9 units. 10 minutes late would be 19 units and 30 minutes would be 39 units.
if Condition
See the code above. We wrote the code using multiple if conditions. It runs in a synchronous manner. This means it’ll check if condition i.e. time == 9 and then second if condition and so on. If the condition becomes true then it’ll print the subsequent print statement else it’ll ignore it and move to the next if condition (or end of the program)
time = 19,
- Since time is not equal to 9, therefore, first if condition becomes false.
- Given time lies under 2nd if condition. So, it’ll become true and it’ll print “10 minutes late”
- 3rd if condition will be false because given time doesn’t lie under this range.
- Similarly, 4th if condition will also become false.
So, only the second if condition will become true and it’ll print “10 minutes late”.
This kind of writing if condition is useful in many areas but it’s not necessary here because in this way it’ll check each and every if condition irrespective of whether the prior has already become true or not. In this example also it’s checking each if condition even when the first if condition becomes true and that’s redundant. Isn’t it?
To solve this, we have other ways of writing the same code.
if else Condition
Let’s take time = 19 and see how this optimizes the above code example.
- First if condition will become false because given time 19 is not equal to 9
- Moving to else,
2.1 First if condition will become true because given time 19 lies under the given range time > 9 and time <= 19. Therefore, it’ll run and print “10 minutes late”.
2.2 Since, first if condition under else block becomes true, therefore, further else block and conditional statements related to it will not execute. Whereas in just if conditional statements, it’s checking each if condition even if one if condition becomes true.
The difference between this code and the above is that we’re skipping the entire block of code if it’s not necessary to check. Let’s see another example.
time = 21,
So, first the condition will become false because time is not equal to 9.
Then it’ll move to another block and check first if the condition in this block i.e. time > 9 and time <= 19. This is also false because time is equal to 21 (given) hence, it’s false. Then it moves to the next else block and checks the first if-condition present in it. Now, this if condition will become true because time is equal to 21 and the condition is if time > 19 and time <= 39 then run this block. So, it’ll print “30 minutes late”. But, it’ll not check the other if condition i.e. if time > 39.
This is a very useful technique to write conditional statements but according to the problem we’re solving this is still not the best way to write it. You can also see how we made the simple-looking code more complex using this unnecessarily. Though it’s quite an improvement (performance-wise) but our code is not clean (which is also necessary).
Let’s improve it with the next conditional statement.
if elif else Condition
Looks clean but does it work? Let’s see.
time = 40
Clearly, first if condition will become false. But imagine what will happen if time is equal to 9? If time is equal to 9, the first if-condition will become true and it’ll print “on time”. Now, it’ll simply reach the end of the code and never ever reach other conditional statements defined here. Do you see the improvement now? Back to the original given time i.e. 40.
When time is equal to 40 and the first if-condition becomes false, it’ll move to the next elif statement (else if) i.e. time > 9 and time <= 19. Clearly, it’s also false. Similarly, other elif statements will also become false. Once, all elif statements become false and we are left with nothing except an else block then all the statements defined inside the else block will run. In this example, it’ll print “Zero marks”.
Let’s take one more example.
time = 29,
- First if condition will become false since time is not equal to 9
- First elif condition will also become false because time doesn’t lie under a given range.
- Second elif condition will become true because time i.e. 29 lies under given range – time > 19 and time <= 39
- Since, code found a true conditional statement, therefore, further conditional statements will not be executed. In the above example, the last else condition will not be executed because of the same reason
So, we’re getting the different outputs according to which conditional statement is true. We discussed 3 types of conditional statements but one way is more appropriate than others according to the problem we’re solving.
Till now, we’re working with an example of one student. In the problem statement, it’s defined that we’ve to perform this same task (which we did above) for ‘n’ number of students.
Say, if n = 10, one way to implement it is that we repeat our code ten times and add an additional if condition to monitor the current value of the student.
Before you get overwhelmed with this lengthy code, let me tell you it’s not the correct way to handle this. It’s written here just to make you understand why it’s wrong and how we can improve it.
We defined an array called students_arrival_time and a counter, student_counter to perform operations for each student. If you see closely, we make use of 1st and 3rd conditional statements i.e. if condition and if elif else. By this example, you can understand how we can combine them and how each one of the ways are important on their own.
We’re doing the same thing as shown in the above code examples, the only change is that we used the 1st conditional statement (if condition) to check for which student we’re performing the operation. Once a student is executed, we’re incrementing the student_counter and because we’re using 1st conditional statement (if condition), it’ll not stop once a condition becomes true, it’ll check other if conditions also. So, using it we’re specifying other if conditions to handle operation for the next student and so on.
BUT as you can see, it’s not the optimal way to handle it. I showed you the code for 2 students and you can assume how lengthy it would become if I’d done it for 10 students. In reality, we’ve not just 10 but more than 1K students in just a single campus. So, do you think it’s the right way?Also, in programming, we have got a DRY principle. Don’t Repeat Yourself principle which says that you shouldn’t write the same piece of code multiple times in multiple places if it’s doing the same thing. And, there are multiple ways to follow this. Obviously, discussing all the ways is out of the scope of this article but there is one way which we can discuss. Yeah, that’s LOOPS!
Loops
- For Loop
- While Loop
Generally, a loop consists of three things. Initialization, condition, and incrementation.
Initialization is used to initialize the starting point of the loop from where it starts performing operations. It could be index, counter, or maybe you could define a range like [2, n] so, that loop will start from 2. And, according to the problem you can modify the loop, there is no compulsion over how you define your initializer as long as it’s syntactically correct.
Condition, it’s the same as we learned above. It is used to define the ending point of the loop. Leaving it empty will make the loop run infinitely until the memory limit of the system exceeds this because the loop doesn’t have any condition specified to come out of the loop.
Incrementation is used to increment the variable (index, counter, etc) to some steps. Leaving it empty can also make the loop run infinite because if we don’t increment the variable, it’ll keep executing operations for the same variable.
Infinite Loop Problem
Let’s understand this with the problem we’re trying to solve using loops (the ‘n’ students problem).
total_students = 10 (assumption)
If we set student_counter to 1 and don’t increment it then it’ll keep running for the same student every time (never ending loop). If we increment it by 1 every time but don’t specify the condition to stop the loop when student_counter reaches 11 (because we have only 10 students) then also it’ll run infinitely. Got it now?
Let’s implement this problem using a for loop.
For Loop
All the code part is same except the for loop statement. Let’s understand this statement in reverse order.
len() gives the length of the array. In our example, it’s used on the students_arrival_time array which has a length of 10.
range(n) function provides first n integers starting from 0 till n-1. It’ll auto increment it by 1 step. In our example, student_counter will become 0 then 1 till the length of array i.e 10 so, student_counter will have value from 0 to 9.
Now, we have defined the variable, student_counter. Initialized it with 0. Loop will run until student_counter doesn’t exceed the length of the array (condition). Using range(), will auto-increment it by 1 step. So, that’s how we’re performing the same operation on 10 different students with the help of just 1 line.
We can perform this using a while loop also. Nothing will change except the syntax because the concept is the same for both. Though, using one over another could be useful in some cases. Will discuss this as a bonus after discussing a while loop.
While Loop
The concept is the same but the way to implement it is completely different. If you see the line,
We initialized the student_counter to zero first and then define the condition. We’re not incrementing the counter in the same line and this is where the difference between both lies. Generally, all the code written using for loop can be done using while loop but it has some special use cases.
Bonus
While loop gives more control to the programmer than for loop (though this is debatable and varied according to the programmer’s style of writing the code). This is because we have the liberty to increment or decrement the counter according to the code requirement. Whereas in for loop, we have to pre-define the increment or decrement counter steps.
Conclusion
So, in this article, we learned about flow control in python. We discussed flow control is nothing but a way to control the code through certain decisions and to monitor which statements need to be executed and which should be skipped. In order to do this, we have learned about types of conditional statements like if condition, if-else condition, and if elif else condition. We also discussed for and while loops and their use cases.