= 4
number
if number % 2 == 0:
print("Number is even")
Number is even
conditional statements, loops, and functions
Any language has a way to control the flow of the program. This is primarily done by using conditional statements, loops, and functions. Flow control is the order in which the program executes statements - think of it like being directed by a traffic policeman on a busy road. The traffic policeman directs the traffic to move in a certain direction, stop, or go back. Similarly, flow control in programming directs the program to execute certain statements based on conditions, loop through a set of statements, or call a function.
Let us start with the basic flow control statements in Python. Say that you want a program to execute a certain block of code only if a certain condition is met. This is where the if
statement comes into play. The if
statement is used to check a condition and execute a block of code only if the condition is True
.
This example takes a number, and if it is divisible by two (the %
operator is the modulo operator, which gives the remainder of the division of two numbers), it prints “Number is even”. What follows the if
statement is called the “condition”, and it is a boolean expression that evaluates to either True
or False
. In fact you can print the evaluation of the condition alone to understand how this works:
But what if the number is not divisible by two? In that case, you can use the else
statement to execute a block of code when the if
condition is False
.
The above is called an if-else
statement. If the condition in the if
statement is True
, the block of code under the if
statement is executed. If the condition is False
, the block of code under the else
statement is executed. This is also an if-else
statement, but with multiple conditions. If the condition in the if
statement is True
, the block of code under the if
statement is executed. If the condition in the elif
statement is True
, the block of code under the elif
statement is executed. If none of the conditions are True
, the block of code under the else
statement is executed.
Let us look at such an example:
number = 5
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
Number is positive
Here we check for two conditions, if the number if larger than zero, smaller than zero or neither (the final else
statement). The elif
statement is short for “else if”, and is used to check multiple conditions. You can have as many elif
statements as you want, but only one if
and one else
statement.
Loops are used to execute a block of code multiple times. There are two types of loops in Python: for
loops and while
loops. A for
loop is used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each element in the sequence. A while
loop is used to execute a block of code as long as a condition is True
.
In the previous section we looked at complex data types like lists and tuples. Let us use them in a for
loop to take a list of numbers, and create a new list with each number squared.
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
squared_numbers.append(number**2) # ** is the power operator
print(squared_numbers)
[1, 4, 9, 16, 25]
The for loop iterates over the list numbers
, and for each number in the list, it appends the square of the number to the list squared_numbers
. for
loops work equally well with other sequences. Let us look at an example with a dictionary. We will take a dictionary with several people, and will calculate the average age in the group.
persons = {"Alice": 21, "Bob": 27, "Charlie": 37}
sum = 0
for person in persons:
sum = sum + persons[person]
average_age = sum // len(persons)
print(average_age)
28
The above code iterates through everyone in the persons
dictionary, and sums everyone ages. Once the for loop is complete, it then calculates the average age by dividing the sum
by the number of people in the list.
len
Function
The len
function takes a sequence (a list, tuple or dictionary) as an argument, and returns the number of elements in the sequence.
The range
function is used to generate a sequence of numbers. It takes three arguments: start
, stop
, and step
. The start
argument is the first number in the sequence, the stop
argument is the number that the sequence stops before, and the step
argument is the difference between each number in the sequence.
It is often used in for
loops to iterate a certain number of times. Let us look at an example where we construct a long list of numbers based on for
and range
.
Besides the for loop, Python also has a while
loop. while
is used to execute a block of code as long as a condition is True
. It is normally used when you do not know how many times you need to execute a block of code, and you only want to stop when a certain condition is met.
The simplest while loop is one that runs forever. This is done by using the True
boolean value as the condition. This is useful when you want to run a program that listens for user input, or a program that runs continuously in the background.
To stop a program that runs forever, you can use the Ctrl+C
keyboard shortcut. In Jupyter notebooks, you can stop the execution of a cell by clicking the stop button in the toolbar.
while True:
print("This will run forever")
break # This will artificially break out of the loop
while False:
print("This will never run")
This will run forever
As a more interesting example, let us calculate how many times we would need to fold a piece of paper to reach the moon. The thickness of a piece of paper is 0.1 mm, and the distance to the moon is 384,400 km. We will fold the paper in half each time.
moon_distance = 384000 * 1000 * 1000 # millimeters
paper_thickness = 0.1 # millimeters
folded_thickness = paper_thickness
folds = 0
while folded_thickness < moon_distance:
folded_thickness *= 2 # This is the same as folded_thickness = folded_thickness * 2
folds += 1
print(folds)
42
A while
loop can also be used in the context of sequences. For example, we can use a while
loop to reverse the order of a list of numbers by using the pop
method of a list.
pop
Method
The pop
method of a list removes the last element of the list and returns it. If you do not provide an index to the pop
method, it will remove the last element of the list.
Sometimes you want to stop a loop before it has finished, or skip the rest of the code in a loop and continue with the next iteration. This is done using the break
and continue
statements. The break
statement is used to exit a loop, and the continue
statement is used to skip the rest of the code in a loop and continue with the next iteration.
Let us look at an example of a for
loop that iterates over a list of numbers, and stops when it reaches a number that is divisible by 3.
Remember the else
in the if-else
statement? It can also be used in a loop. The else
statement in a loop is executed when the loop has finished iterating over the entire sequence. It is not executed if the loop is exited using a break
statement. Let us put that to good use from the previous example.
numbers = [10, 17, 22, 31, 56]
for number in numbers:
if number % 3 == 0:
print(number)
break # This will break out of the for loop
else:
print("No number was divisible by 3")
No number was divisible by 3
The continue
statement is used to skip the rest of the code in a loop and continue with the next iteration. This is useful when, for example, you want to skip certain elements in a sequence. Let us look at an example where we take a list, and build another list without any numbers which are divisible by 3.
The match
statement is used to compare a value against a set of patterns, and execute a block of code based on the pattern that matches. It is similar to a series of if-elif-else
statements, but is more concise and easier to read. Here is a practical example of a match
statement that takes a number, and prints a string based on the number.