Control flow structures like if statements and for loops are powerful ways to create logical, clean and well organized code in Python. If statements test a condition and then complete an action if the test is true. For loops do something for a defined number of elements. List comprehensions are Python’s way of creating lists on the fly using a single line of code.
Can You Put a For Loop in an If Statement?
You can put an if statements inside for loops. For example, you can loop through a list to check if the elements meet certain conditions.
There are two parts to the structure of flow statements in Python. One is the parent statement line, which defines the statement with “if” or “for” keywords. This line must end with a colon. The second is the child statement, which contains the code block to be implemented if the condition is true in the case of an if statement, or implemented repeatedly in the case of a for loop. Child statements must be indented with four white spaces (or a tab space) at the beginning, otherwise an IndentationError
will occur.
parent statement:
child statement or code block indented with 4 spaces
What Is an If Statement?
This is a statement that begins with the “if” keyword followed by a condition that should evaluate to either True
or False
, followed by a colon. The code block comes in the second line and is indented in the beginning with four white spaces. This is the code that will be implemented if the condition is met.
If condition:
code block
Note in the example below that if the condition is false, nothing will be displayed. There is no error.
if 5 > 1:
print('True, Five is greater than One')
### Results
True, Five is greater than One
How to Write an If-Else Statement
You can also include an else statement with code to be implemented if the condition is false.
If condition:
code block
else:
code block
Below is an example of an if-else statement.
if 'a' > 'b':
print('True')
else:
print('False, "a" is not greater than "b"')
#Results
False, "a" is not greater than "b"
How to Write an If-Elif-Else Statement
You can check for many other conditions using elif, which is short for else if. The final else evaluates only when no other condition is true. Else and elif statements are optional, and you can have one without the other. The first if statement, however, is a must.
age = 60
if age >= 55:
print("You are a senior")
elif age < 35:
print("You are a youth")
else:
print("You are middle aged")
### Results
You are a senior
What Are For Loops?
A for loop introduces the concept of iteration, which is when a process is repeated over several elements such as those in a list.
A for loop contains four components; a for keyword, an iterable such as a list that contains the elements to loop through, a variable name that will represent each element in the list, and the code block that will run for every element. The code block is indented with four white spaces.
for variable_name in list:
code block
The two examples below show for loops that iterate through a list and then print each element in the list. Note that I have included the print results in the same line to save space. But in practice each element is printed on its own line because the print()
function defaults to adding a new line at the end of each print.
for name in ['sue', 'joe', 'gee']:
print(name)
for num in [1,2,3,4,5]:
print(num+1)
### Results
sue joe gee
2 3 4 5 6
Introducing Range()
This function is used to generate integer lists that can be used in for loops. You can create a list by range(stop)
, range(start,stop)
or range(start, stop, step)
. Start (optional)
defines the first number in the sequence. The default is zero. Stop (not optional)
defines where the list ends, but this number is not included in the list. Therefore, the last number in the sequence is stop minus one. Step (optional)
is the increment for each number in the list and the default is one. For example, range(10)
creates a list from zero to nine, range(2,10)
creates a list from two to nine and range(1,10,2)
creates the list one, three, five, seven, nine. Note that range()
creates integer lists only and will throw a TypeError
if you pass it anything other than an integer.
for i in range(5):
print(i)
for i in range(2, 9):
print(i)
for i in range(0, 11, 2):
print(i)
### Results
0 1 2 3 4
2 3 4 5 6 7 8
0 2 4 6 8 10
You can also iterate lists in reversed order using reverse(list)
.
l = [’one’,’two’, 'three’]
for rev in reversed(l):
print(rev)
for r in reversed(range(95,101)):
print(r)
### Results
three two one
100 99 98 97 96 95
How to Write a Nested Control Flow
You can nest if statements inside for loops. For example, you can loop through a list to check if the elements meet certain conditions.
ages = [78, 34, 21, 47, 9]
for age in ages:
if age >= 55:
print("{} is a senior".format(age))
elif age < 35:
print("{} is a youth".format(age))
else:
print("{} is middle aged".format(age))
You can also have a for loop inside another for loop. In this example, for every element in the first list, we loop through all elements in the second list.
first_names = ['john','sam', 'will']
last_names = ['white', 'smith', 'alexander']
for fname in first_names:
for lname in last_names:
print(fname, lname)
### Results
john white
john smith
john alexander
sam white
sam smith
sam alexander
will white
will smith
will alexander
What Are List Comprehensions?
List comprehensions are a way to construct new lists out of existing lists after applying transformations to them.
Every list comprehension has an output, usually but not necessarily, transformed, and a for loop contained within square brackets. We use square brackets because we are constructing a list.
[transformed_l for l in list]
To construct a set or tuple, enclose the list comprehension with {} or () respectively.
The first code below multiplies each element in the original list by two to create a new list. num*2
is the desired output, followed by the for loop. The second code does not transform the elements and outputs the same list.
print([num*2 for num in [2,4,6,8,10]])
print([num for num in [2,4,6,8,10]])
### Result
[4, 8, 12, 16, 20]
[2, 4, 6, 8, 10]
Conditional Logic
You can add an if statement at the end of a list comprehension to return only items which satisfy a certain condition.
[output for l in list if condition]
For example, the code below returns only the numbers in the list that are greater than two.
[l for l in list if l>2]
This code returns a list of heights greater than 160 cm.
heights = [144, 180, 165, 120, 199]
tall = [h for h in heights if h > 160]
print(tall)
### Results
[180, 165, 199]
You can have conditional outputs with if-else in the output part. For example, you can classify the elements in a list by creating a new list that holds what class each element in the original list belongs to. In this case, you must have both if and else keywords. Otherwise, a SyntaxError
is thrown. Elif does not apply here.
[output if condition else output for l in list]
The code below creates a list from zero to nine. Then we define a list comprehension, which iterates through the list and outputs either “even” or “odd” for every number in the list. We use the modulo (%
) operator that returns the remainder of a division. A number is even if the remainder of division by two is zero. Otherwise, the number is odd.
nums = list(range(10))
num_classes = ['even' if num%2 == 0 else 'odd' for num in nums]
print(num_classes)
### Results
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Functions Explained
We cannot talk about flow control without mentioning functions. Functions enable you to create reusable blocks of code. They create modularity, or separate code blocks that perform specific functions, and keep your code organized.
Functions start with a def keyword, then a desired function name, parentheses () and a colon to end the parent statement. Optional arguments can be provided inside the parentheses, which are just variables you pass into the function. The next line contains the code block indented with four white spaces. You can have an optional return statement in the last line of the code block that will be the result(output)
of the function.
def name():
code block
return value
You can type a function’s name and then parentheses to call it. If the function takes in arguments, provide them inside the parentheses when calling it.
name()
The following code defines a function which prints ‘Hi there’ when called. This code block does not have a return statement.
def hello():
print('Hi there')
hello()
### Results
Hi there
The code below defines a function that takes in an integer value and squares it. It does have a return statement.
def square_number(num):
return num*num
five_squared = square_number(5)
print(five_squared)
### Results
25
A function must contain a code block. This can be just a return statement, code that does something, or the pass keyword that does nothing. If there is no return statement, the function will return “None” by default.