Control flow statements in python regulate the order of execution of commands. Conditional statements and loops are the common types of control flow statements used in python.
This is the third article in our series Python for Data Science. In our first article, we introduced how data science is changing the world and why Python is preferred by a majority of data science practitioners. In our second article, we explained some of the fundamental building blocks of programming in python – expressions, variables, data types, operators, comments, input/output functions, etc.
By the end of this article, you’ll have an understanding of the different control flow statements used in python.
Table of Contents
- Conditional Control Flow Statements
- If-else statement
- If-elif-else statement
- The while loop
- The for loop
- Break and Continue
- Recommended Reading
Conditional Control Flow Statements
Conditional statements allow you to execute a section of code based on some boolean conditions.
if-elfi-else are the common conditional constructs used in python.
Used to execute a section of code based on a condition,
if statements can be used without the use of an
elif part. The following example illustrates the control flow during execution of an if statement.
# some instructions age = 19 voting_eligibility = False # Make the person eligible for voting if she's 18 and above if age >= 18: # Execute if condition is true print("Eligible for voting") print("*****") voting_eligibility = True # Continue with code execution print("Age: ", age) print("Is eligible for voting: ", voting_eligibility)
In the above example, we determine the eligibility of a person to vote based on her age. By default, the eligibility is set to
if condition comes in handy to update this eligibility if the age of the person is 18 or above. The control shifts to the part inside the
if block if the condition evaluates to True. The following is output generated on executing the above code:
Eligible for voting ***** Age: 19 Is eligible for voting: True
If the condition is evaluated to
False the instructions inside the
if block is ignored and the control continues on to the next section. For example, if age in the above example is set to 15, we get the following output on execution.
Age: 15 Is eligible for voting: False
else statement is often used in conjunction with the
if statement. It’s used to direct the control to execute some instructions if the condition in the
if statement evaluates to
False. The following example illustrates the if-else control flow.
# Determine the traffic based on the fraction of roadways covered traffic_fraction = 0.3 if traffic_fraction > 0.5: print("High Traffic!") else: print("Low Traffic")
In the above example, we determine traffic based on the fraction of roadways covered. The variable
traffic_fraction represents the fraction of the road-area covered. The above code gives the following ouput.
The traffic_fraction, 0.3, is not greater than 0.5 hence the condition in the
if statement evaluates to
False and since we have an else block, the control shifts to execute the instructions inside it.
if-elif-else statement in python is the substitute for the
switch statement found on languages like Java/C++. The
elif statement allows you to check for another condition should the condition in the
if statement evaluate to
False. You can have multiple
elif conditions in a single
During execution, the control evaluates the different conditions from top to bottom, if a condition evaluates to
True, the instructions inside the matching segment are executed and the code exits the
if-elif-else construct ignoring the subsequent conditions and instructions inside the construct. If a none of the conditions evaluate to
True, the instructions inside the
else segment is executed. The following example illustrates the
if-elif-else control flow.
# Determine the traffic based on the fraction of roadways covered traffic_fraction = 0.3 if traffic_fraction > 0.5: print("High Traffic!") elif traffic_fraction >= 0.25 and traffic_fraction < 0.5: print("Medium Traffic") else: print("Low Traffic")
We updated the
if-else example to include a third categorization of the traffic based on the road area covered. The following is the result of executing the above code:
In the above example, the control first checks the
if condition, since 0.3 is not greater than 0.5, it evaluates to
False. Now the control moves on to evaluate the
elif condition, since 0.3 is in fact greater than or equal to 0.25 and less than 0.5 the condition evaluates to
True and the statements inside the
elif segment are executed. Now, since a condition has evaluated to
True, the control moves out of the
if-elif-else construct altogether.
Loops are used when we want to repeat the execution of certain instructions. In python,
while statements are used to iterate over the instructions.
The while loop
while loop iterates over the instructions as long as the condition specified with the while statement evaluates to
During execution, first, the condition alongside the while statement is evaluated. If the condition evaluates to
True, the segment inside the loop gets executed, the control then again shifts to evaluate the condition and the process is repeated until the condition evaluates to
False. The following example illustrates the functioning of a while loop.
# while loop example, print the first five natural number n = 1 while n <= 5: # instructions to iterate over # print the number print(n) # update the number n = n+1
In the above example, we use a
while loop to print the first five natural numbers. The above code generates the following results:
1 2 3 4 5
On execution, first the condition
n <= 5 is checked, since initially, n = 1, and 1 is less than 5, the control executes the statements inside the while loop construct – printing n and incrementing it by one. This continues until the value of n becomes 6, now, when the condition is checked, it evaluates to
False and the while statement ends.
It’s important to note that the code inside the while loop should eventually make the condition
False. If not, it can result in an infinite loop unless an exception is raised or a break statement is met.
The for loop
In python, the
for statement is used to iterate over the items of a sequence (example, list, set, string, etc.), in the order they appear in the sequence.
The following example illustrates the functioning of a for loop:
# for loop example: print all the items in a list names = ['Nikhil', 'Sam', 'Shyam'] for name in names: # instructions to be iterated over print(name)
The above code generates the following results:
Nikhil Sam Shyam
In the above example, the for loop is used to iterate over the items in the list
names and print them. We use the membership operator
in to get the elements in the list. For more on operators refer to our guide on operators in python.
Break and Continue statements
continue statements are used to manipulate the flow control inside the loop.
break statement: The
break statement causes the control to break out of the innermost enclosing of the loop. The following example illustrates this better:
# break statement example for i in ['a', 'b', 'c']: for j in [1, 2, 3, 4]: if j >= 3: break print(i, j)
When a break statement is encountered, the control stops the execution of the immediate loop and moves out. The above code gives the following result:
a 1 a 2 b 1 b 2 c 1 c 2
You can see that in the above example, it is the inner loop that is affected by the break statement such that we do not see values of j beyond 2. Whereas, the outer loop executes completely iterating over all the values from a to c.
continue statement: The
continue statement, when encountered, forces the loop for the next iteration ignoring the subsequent instructions. The following example illustrates the working of the
# continue statement example for i in [1,2,3,4]: if i==3: continue print(i)
The above code gives the following result:
1 2 4
In the above example, the
continue statement is encountered when
3, this forces the loop into the next iteration without printing the value of
i hence we do not see 3 in the output.
In this tutorial we looked at the different control statements used in python. These control statements are used to manipulate the order of execution of commands so as to accommodate the logic for a programming task. If you’d like to dive deeper, we recommend the following (opening available) resource to supplement the topics covered –
- Chapter-2 of the book Automate the Boring Stuff with Python. This book is specially designed to have an implementation first approach. The online version of the book is freely available.
- Python docs on control flow statements.
In the next article in this series we’ll be covering functions in python.
If you found this article useful do give it a share! For more such articles subscribe to us.
In the next article in this Python for Data Science series, we’ll be covering functions in python. Stay tuned and happy learning!