4. Conditionality and Repetition

4. Conditionality and Repetition#

You will quickly find out that in your programming experience, you will spend quite some time writing conditional statements or looping through items. Therefore, it’s very important that you understand what these statements do and how to properly use them.

Conditionality#

The if statement is based on a boolean operation: if the first condition is executed it means that the condition is True, otherwise, the program moves on to the next statements until either a True statement or the end of the flow (else, if included). The flow chart below illustrates the conditional process with one if, two elif and one else statements.

Picture

Let’s see some examples.

# Simple if statement
if True == 1:
    print('True')
    
if False == 0:
    print('False')
True
False
# Now let's execute this cell...do you know why the cell is not printing anything?
if ():
    print('This condition is not True')
# But this cell does return something
if not ():
    print('This condition is True')
This condition is True

As you might have guessed, Python casts boolean values in different ways. Note that in Python 3, True and False are keywords and cannot be reassigned to another value, e.g., False = 5 will raise an error.

Here are values that are built-in objects considered False:

- constants defined to be false: None and False.
- zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
- empty sequences and collections: '', (), [], {}, set(), range(0)

Read more about Truth Value Testing here.

# Note: the 'else' statement is optional and may not be specified
a = 50 
# the % is the modulo operator finding the remainder after the division
# in this case, a divided by 5 leaves 0
if a%5==0:
    print('a is divisible by 5')
a is divisible by 5
# Now let's see more complex statements
# Change the values of exam_score and assignment to see how the outcome changes

exam_score = 30
assignment = 'C'

if exam_score >= 80:
    if assignment == 'A':
        print('You passed the exam with the highest grade.')
    elif assignment =='B':
        print('You passed the exam with the second highest grade')
    else:
        print('You passed the exam with the third highest grade')
elif 40 <= exam_score < 80:
    if assignment == 'A' or assignment == 'B':
        print('You did well in the assignment but not in the exam, you have a second attempt in 30 days')
    else:
        print('You barely passed the exam')
else:
    print('You failed the exam!')
You failed the exam!

Exercise: Change the previous code so that if a student receives an exam score between 35 and 40 (not included) and assignment grade A, the code returns “You almost passed”.

# Your code here

Repetition#

The for loop is used to iterate through items, which could be stored in a tuple, list, dictionary and so on (we will get familiar with all of these data structures in week 2, so if you don’t know these terms don’t worry). These kinds of loops are helpful in a multitude of operations, for example when encountering a nested loop, where list comprehensions would make the code less transparent and harder to read. Remember that, particularly when working in a team, code readability is very important.

Here we also introduce a new, very useful, function: the zip function. This function is used to simultaneously loop through multiple elements, for example through two lists.

# loop through students and grades in the two given lists through the 'zip' function
for student, grade in zip(['Anna', 'Mary', 'Thomas'], [7, 12, 10]):
    # if the student's initial is M and their grade is 12
    if student.startswith('M') and grade == 12:
        # print the name of the student
        print(student)
    else:
        # otherwise print that it is not Mary
        print(student, 'is not Mary')
Anna is not Mary
Mary
Thomas is not Mary
# In this example we will use a library called Numpy
import numpy as np

# we initialize a matrix with random samples from a uniform distribution [0, 1) of shape 2x3 (rowsxcolumns)
matrix = np.random.rand(2,3)

# uncomment the following lines to investigate the data
# print(matrix.shape)
# print(matrix)

# loop through the elements of the matrix
for row in matrix:
    print('Row', row)
    # loop through each element in the row
    for elem in row:
        print('Element', elem)
    print()
Row [0.00881336 0.60460902 0.42609128]
Element 0.00881335551935869
Element 0.6046090204644909
Element 0.42609127820816095

Row [0.8919357  0.83208568 0.74294669]
Element 0.8919357029555318
Element 0.8320856773069047
Element 0.7429466851439546

The while loop is used to iterate through elements for as long as a certain condition is valid.

# set a condition
limit = 10

c = 0
while c <= limit:
    c+=1
    print(f"Our total amount c is: {c}, so the condition is within the limit")
Our total amount c is: 1, so the condition is within the limit
Our total amount c is: 2, so the condition is within the limit
Our total amount c is: 3, so the condition is within the limit
Our total amount c is: 4, so the condition is within the limit
Our total amount c is: 5, so the condition is within the limit
Our total amount c is: 6, so the condition is within the limit
Our total amount c is: 7, so the condition is within the limit
Our total amount c is: 8, so the condition is within the limit
Our total amount c is: 9, so the condition is within the limit
Our total amount c is: 10, so the condition is within the limit
Our total amount c is: 11, so the condition is within the limit

But be careful about infinite loops!

# infinite loop: interrupt execution!

#while True:
#    print('This will keep running...')

Continue and Break#

Sometimes, it can be useful to ignore certain conditions or parts of the code. In this case, you can use the continue and break commands. Depending on what you want to achieve, you may use either of these commands.

For example,

  • continue can be used to skip a certain condition in a loop and move to the next

  • break exits the current execution (e.g., in a loop) and moves to the next code block.

# let's investigate what 'continue' does
for i in range(15):
    if i > 7:
        print(i)
    else:
        #if this condition is True, we continue to the next iteration
        continue
8
9
10
11
12
13
14
# create a list of reactors
reactors = ['batch', 'continuous stirred tank', 'plug flow']

# create a new list, we will add items to this list until a certain element is reached, then we break the loop
new_reactors = [] 
for reactor in reactors:
    # append items
    new_reactors.append(reactor)
    if reactor == 'continuous stirred tank':
        # if the condition is met, break the loop
        break

if 'batch' in new_reactors:
    # print the new list
    print(new_reactors)
['batch', 'continuous stirred tank']

Here you can see that we used the break command to exit the loop once we reached our goal, which was to terminate the loop once ‘continuous stirred tank’ was added to new_reactors list.

References: