Control Flow Tools in Python
Learn about control flow tools in Python including if statements, for loops, and while loops.
Introduction
Control flow tools in Python change the flow of how code is executed by the Python interpreter.
Since the Python interpreter executes code in a line by line manner, control flow tools help dictate what line(s) of code should run in a Python program.
There are different types of control flow tools available to us in Python:
- if statement
- if-else statement
- if-elif-else statement
- for loop
- while loop
- pass, continue and break statement
Python if statement
The Python if statement is a conditional statement responsible for executing programming blocks based on a specified condition.
if condition:
statement(s)
if 10 > 4:
print("The if statement is executed.")Here is an example of a Python if statement where the condition is evaluated as False so no output is produced.:
if 10 < 4:
print("The if statement is executed.")if 10 > 4: print("The if statement is executed.")Python if-else statement
The Python if-else statement contains an added instruction in the Python if statement dictating what code should be executed if the condition is evaluated as False.
if condition:
statement(s)
else:
statement(s)
Here is an example of a Python if-else statement where the if condition is evaluated as True:
if 10 > 4:
print("The if statement is executed.")
else:
print("The else statement is executed.")Here is an example of a Python if-else statement where the if condition is evaluated as False:
if 10 < 4:
print("The if statement is executed.")
else:
print("The else statement is executed.")Python if-elif-else statement
The Python if-elif-else statement contains added if conditions in an if-else statement. The syntax for writing an if-elif-else statement in Python is as follows:
if condition1:
statement(s)
elif condition2:
statement(s)
elif condition_n:
statement(s)
else:
statement(s)
Here is an example of a Python if-elif-else statement where the if statement is executed:
if 10 > 4:
print("The if statement is executed.")
elif 10 == 4:
print("The elif statement is executed.")
else:
print("The else statement is executed.")Here is an example of a Python if-elif-else statement where the elif statement is executed:
if 10 < 4:
print("The if statement is executed.")
elif 10 == 10:
print("The elif statement is executed.")
else:
print("The else statement is executed.")Here is an example of a Python if-elif-else statement where the else statement is executed:
if 10 < 4:
print("The if statement is executed.")
elif 10 == 4:
print("The elif statement is executed.")
else:
print("The else statement is executed.")Here is an example of a Python if-elif-else statement where the second elif statement is executed:
if 10 < 4:
print("The if statement is executed.")
elif 10 == 4:
print("The first elif statement is executed.")
elif 10 == 10:
print("The second elif statement is executed.")
else:
print("The else statement is executed.")Note that you can have as many elif statements as you want.
Pass statement
The pass statement is one of those control flow tools in Python that does nothing. It can be used when a statement is required syntactically, but the program requires no action.
if 5 == 5:
pass # this does nothingPython For Loop
The Python for loop statement is a control flow tool used to iterate over the items of any sequence (a list or a string) in the order that they appear in the sequence.
The syntax of for loop in Python is slightly different from what you may have used in other programming languages, such as C or C++. The syntax for writing a for loop in Python is as follows:
for variable in iterable_sequence:
statement(s)
Here is an example of a Python for loop that iterates over a given list of numbers and prints them out:
# Defining a list of integers
list_of_numbers = [10, 15, 20]
# for statement
for number in list_of_numbers:
print(number)As you may have noticed, creating a list manually is tiresome when we have to iterate multiple times. So, it is more common to use a range() function for iterating a for loop.
print(range(0, 10, 1))
print(list(range(0, 10, 1)))Using this in a for loop would look like this:
# for statement
for number in range(0, 10):
print(number)From For Loops to List Comprehension
So far, we have used for loops mainly to do something with each item (like printing).
Very often, however, we use a for loop to build a new list from an existing sequence.
# Creating a list using a for loop
squares = []
for number in range(1, 6):
squares.append(number * number)
print(squares)Python provides a shorter and more expressive way to write this pattern using list comprehension.
# The same logic using list comprehension
squares = [number * number for number in range(1, 6)]
print(squares)A list comprehension follows this general pattern:
[expression for item in iterable]
It reads almost like English: “Create a list of expression for each item in the iterable.”
List Comprehension with Conditions
List comprehensions can also include conditions to filter values.
# Getting only even numbers
evens = [number for number in range(1, 11) if number % 2 == 0]
print(evens)This replaces a common for-loop pattern that uses if statements inside the loop.
Furthermore, it is also possible to nest loops inside one other as shown in the following example:
# Declaring two lists
outer_list = [1, 2]
inner_list = ['a', 'b']
# Outer for-loop
for x in outer_list:
# Inner for-loop
for y in inner_list:
print(x)
print(y)Python While loop
The Python while loop is an iterator used to execute a block of statements until the specified condition is matched. It is one of the most used control flow tools in Python.
The syntax for writing a while loop in Python is as follows:
while condition:
statement(s)
Here is an example of a while loop:
x = 10
while x < 35: # run a loop while x is less than 35
x = x + 5
print(x)Please be mindful that if the condition is always True, then, the while loop will not stop and your program will be stuck in an infinite loop.
Python Break and Continue statements
The Python break and continue statements alter the flow of a normal loop.
The break statement breaks out of the innermost enclosing a for or while loop, whereas, the continue statement continues with the next iteration of the loop. In other words, the continue statement escapes the block of the statement below it and starts with the next iteration of the loop.
Here is an example of how the Python break and continue statements work:
actions = ["wake", "wash", "eat", "work", "play", "sleep"]
for action in actions:
if action == "sleep":
break # if the action is sleep, this would terminate the loop completely
elif action == "play":
continue # if the action is play, the loop continues to next iteration
else:
print(action)