Conditions and loops in Python#
Conditions#
The if
statement (a control flow tool), followed by an expression, can be used to execute code conditionally. That means only if that expression is True
. For such expressions, logical operators from mathematics can be used.
See also:
Let’s take a look at such expressions first:
a = 3
b = 4
# equal
a == b
False
# not equal
a != b
True
# greater
a > b
False
# less
a < b
True
# greater equal
a >= b
False
# less equal
a <= b
True
Conditions with if, else, elif#
The if
statement is used to test a condition, defined by an expression: if the condition evaluates to True
, the code block within the if
statement is executed; otherwise, the code block is skipped.
The else
statement can be used to execute a block of code if the condition in the if
statement is False
.
The elif
(short for ‘else if’) statement can be used to check multiple conditions in sequence, where each condition is checked only if the previous ones were False
.
# Example of if, else, and elif conditions
x = 15
if x < 10:
print('x is less than 10')
elif x == 10:
print('x is equal to 10')
else:
print('x is greater than 10')
x is greater than 10
Exercise:#
Write a program that checks if a number is positive, negative, or zero.
Loops: for and while#
Loops (also a control flow tool) are used to execute a block of code repeatedly. In notebooks, we just may execute a code cell the desired number of times. But it’s better to use loops, and in Python, there are two main types:
For Loop: This loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).
While Loop: This loop repeats a block of code as long as a specified condition is true.
See also:
The for loop#
For looping over elements of a sequence, we can use for
on the sequence and need to define the currently examined element.
# Example of a for loop
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
apple
banana
cherry
Exercise:#
We can also use the range()
method, to iterate over numbers. Define a for loop to print every second number from 0 to 10:
If we want to know the index of an element in the list as well, the built-in enumerate
function comes in handy:
# numbering and iterating through collections
for index, animal in enumerate(["Dog", "Cat", "Mouse"]):
print(f"The animal number {index} in the list is {animal}")
The animal number 0 in the list is Dog
The animal number 1 in the list is Cat
The animal number 2 in the list is Mouse
Using the built-in zip
function, we can iterate over two lists in parallel, with pair-wise elements like this:
# going through arrays pair-wise
measurement_1 = [1, 9, 7, 1, 2]
measurement_2 = [4, 5, 5, 7, 4]
for m_1, m_2 in zip(measurement_1, measurement_2):
print(f"Paired measurements: {m_1} and {m_2}")
Paired measurements: 1 and 4
Paired measurements: 9 and 5
Paired measurements: 7 and 5
Paired measurements: 1 and 7
Paired measurements: 2 and 4
Use for loops to generate lists#
We can generate lists using for loops. The conventional way of doing this involves multiple lines of code:
# we start with an empty list
numbers = []
# ...and append elements
for i in range(0, 5):
numbers.append(i * 2)
print(numbers)
[0, 2, 4, 6, 8]
We can also write that shorter. The underlying concept is called generators
.
This is also part of what the community calls “The Pythonic Way”—making use of available classes and concepts to write short, clean, and understandable code.
numbers = [i * 2 for i in range(0, 5)]
print(numbers)
[0, 2, 4, 6, 8]
The while loop#
The while
loop keeps executing as long as the given condition is True
. It checks a condition before each iteration, similar to the if statement. It will interrupt the execution as soon as the condition is no longer true. Make sure to update the condition inside the loop accordingly, or it might result in an infinite loop.
# Example of a while loop
count = 0
while count < 5:
print('Count:', count)
count += 1
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Exercise#
Write a while loop that halves and prints a given number as long as this number is greater than 1.
Interrupting loops#
You can interrupt loops at specific points in your code using the break command:
for i in range(10):
print(i)
if i > 3:
break
0
1
2
3
4
Skipping iterations in loops#
If you want to skip iterations, you can use the continue statement. That often makes sense in combination with an if:
for i in range(0, 10):
if (i >= 2) and (i <= 7):
continue
print(i)
0
1
8
9
Exercise#
Assume you have a list of filenames, and you want to do something with them, for example, print them out. Program a for loop which prints out all file names that end with “tif”. You may want to use a built-in method for strings.
file_names = ['dataset1.tif', 'dataset2.tif', 'summary.csv', 'readme.md', 'blobs.tif']