6. Conditional Blocks#

6.1. What is a Conditional Block?#

Conditional blocks allow your programme to make decisions. They control the flow of execution depending on whether a certain condition is True or False. You can either have conditional statement, where a block is carried out once if a condition is met, or a conditional loop where the block is carried out repeatedly as long as the condition is true.

The most common conditional blocks are:

  • if-else statement: carries the block out if a condition is True and other else (perhaps) another block

  • while loop : carries out the block repetitively in a loop as long as some condition is true

  • for loop: carries out the same block for different variables

A conditional block consists of the condition and the body. The condition is defined by the key word (if,for, and while) + the condition (using conditional operators) + colon :. Afterwards the body, which is the code block that should be executed, is given, which is indented to show that it is the child of the condition. The body stops when the code is no longer indented but on the same line as the condition again.

You have already seen an example of such a block in the first chapter: the if statement to check the patient’s age.

Remainder About Indentation

Indentation is crucial in Python.
Lines that are part of a block must be indented, usually by 4 spaces or 1 tab.

6.2. The if - else Statement#

The if statement checks a condition. If the condition is True, the block of code underneath it (properly indented) will run. Once the block is finished, it will carry on to the next block of code underneath.

age = 20

if age >= 18:
    print("The patient is an adult.")
The patient is an adult.

Sometimes you want to run one block of code if a condition is True, and a different block if it is False. You can use the else statement for this. After the end of the if block, create a new block with the same indentation as the if but with the key else followed by a colon (i.e., else:). No conditional statement is needed since it just runs if the statement above is False.

age = 16

if age >= 18:
    print("The patient is an adult.")
else:
    print("The patient is a minor.")
The patient is a minor.

Sometimes you do not only have a binary choice but you have several possible code blocks to run. For these cases, the elif (short for ā€œelse ifā€) key exists to test for additional conditions after the initial if statement. You can have as many elif statements as you want, each with a different condition, as long as they are after the if and before the else. Python checks each condition from top to bottom and runs the first block where the condition is True (all other blocks are ignored). If none of the if or elif conditions are met, then the else block is run (if it exists - otherwise none of the blocks are run).

Try to play around with different ages and see which block will be run in the following example:

age = 70

if age < 13:
    print("The patient is a child.")
elif age < 20:
    print("The patient is a teenager.")
elif age < 65:
    print("The patient is an adult.")
else:
    print("The patient is a senior.")
The patient is a senior.

6.3. The while Loop#

A while loop repeatedly executes a block of code as long as a given condition is True. Unlike an if statement, which runs the block just once if the condition is satisfied, the while loop returns to the condition after each execution of the block. If the condition is still True, it runs the block again. This process continues until the condition becomes False. The condition itself is written similarly to an if statement and typically involves checking the value of a predefined variable.

Infinite loops

Make sure you update the value of the variable somewhere in the while loop body.

Otherwise your variable is never changed (i.e., it remains True forever) and the while loop is stuck in an infinite loop. This often leads to the code eventually crashing.

If you ever run some code with a while loop and it takes surprisingly long, it is probably stuck. Force the code to stop and double check your block. Check how your variable gets updated and print it at the end of the block to see how it changes through each iteration.

age = 1

while age < 18:
    print("Another year until adulthood: the patient is currently", age)
    age += 1 # update the age!

# Left the while loop once age >= 18
print("The patient is an adult. They are", age, "years old.")
Another year until adulthood: the patient is currently 1
Another year until adulthood: the patient is currently 2
Another year until adulthood: the patient is currently 3
Another year until adulthood: the patient is currently 4
Another year until adulthood: the patient is currently 5
Another year until adulthood: the patient is currently 6
Another year until adulthood: the patient is currently 7
Another year until adulthood: the patient is currently 8
Another year until adulthood: the patient is currently 9
Another year until adulthood: the patient is currently 10
Another year until adulthood: the patient is currently 11
Another year until adulthood: the patient is currently 12
Another year until adulthood: the patient is currently 13
Another year until adulthood: the patient is currently 14
Another year until adulthood: the patient is currently 15
Another year until adulthood: the patient is currently 16
Another year until adulthood: the patient is currently 17
The patient is an adult. They are 18 years old.

6.4. The for Loop#

Like the while loop, the body of a for loop runs multiple times. However, instead of manually updating a variable inside the loop, the for loop defines in advance which values the variable should take. Each time the loop runs, the variable is automatically updated to the next value in a sequence, and the loop ends when all values have been used.

The loop header follows the pattern: variable + in + data structure — for example, age in ['child', 'adult']. You don’t need to define the variable beforehand, because the for loop automatically creates and assigns it the first value from the data structure when the loop begins.

# Iterate over a list
print('Iterating over a list')
for age in ['child', 'teenager', 'adult', 'senior']:
    print("The patient is a(n)", age)

print()
print('Iterating over a set')
# Iterate over a set - remember that sets are unordered so the variable is assigned randomly to each value
for age in {'child', 'teenager', 'adult', 'senior'}:
    print("The patient is a(n)", age)
Iterating over a list
The patient is a(n) child
The patient is a(n) teenager
The patient is a(n) adult
The patient is a(n) senior

Iterating over a set
The patient is a(n) adult
The patient is a(n) child
The patient is a(n) teenager
The patient is a(n) senior

To be able to interate through a range of numbers, we can use the range(start, end, step) function. It returns a list of integers. It takes in as an argument:

  • the starting value: optional (default to 0) - The first value the variable is set to

  • the end value: mandatory - The loop is carried out as long as the variable is less than this value (not less than or equal to!)

  • the step size: optional (defaults to 1) - For every loop this value is added to the variable

print('Normale range function')
for age in range(1, 6, 2):
    print("The patient is", age, "years old.") 


print()
print('Range without defined step size (default is 1) or start value (default is 0)')
for age in range(6):
    print("The patient is", age, "years old.") # Note that the last number is not included in the range
Normale range function
The patient is 1 years old.
The patient is 3 years old.
The patient is 5 years old.

Range without defined step size (default is 1) or start value (default is 0)
The patient is 0 years old.
The patient is 1 years old.
The patient is 2 years old.
The patient is 3 years old.
The patient is 4 years old.
The patient is 5 years old.

We can also iterate through a dictionaries keys or values. Using the in condition as for lists would iterate through the dictionaries keys. The keys can then be used to access the corresponding value. Or you can use the method .values() on the dictionary when using the in condition to directly loop through its values. Lastly, to iterate through keys and values at the same time you can use the .items() method. Note that since we get two entries for each loop, you need to define two variables in the for condition block:

# Define a dictionary
age_dict = {
    'child': 10,
    'teenager': 16,
    'adult': 30,
    'senior': 70
}
print("The dictionary is:", age_dict)

print()
print("Iterating over a dictionary keys:")
# Iterate through the dictionary keys
for key in age_dict:
    print("The patient is a(n)", key)
    print("They are", age_dict[key], "years old.")

print()
print("Iterating over a dictionary values:")
# Iterate through the dictionary values
for value in age_dict.values():
    print("The patient is", value, "years old.")

print()
print("Iterating over a dictionary keys and values at the same time:")
# Iterate through the dictionary keys and values
for key, value in age_dict.items():
    print("The patient is a(n)", key)
    print("They are", value, "years old.")
The dictionary is: {'child': 10, 'teenager': 16, 'adult': 30, 'senior': 70}

Iterating over a dictionary keys:
The patient is a(n) child
They are 10 years old.
The patient is a(n) teenager
They are 16 years old.
The patient is a(n) adult
They are 30 years old.
The patient is a(n) senior
They are 70 years old.

Iterating over a dictionary values:
The patient is 10 years old.
The patient is 16 years old.
The patient is 30 years old.
The patient is 70 years old.

Iterating over a dictionary keys and values at the same time:
The patient is a(n) child
They are 10 years old.
The patient is a(n) teenager
They are 16 years old.
The patient is a(n) adult
They are 30 years old.
The patient is a(n) senior
They are 70 years old.

Using the .items() method on the dictionary allowed you to loop through keys and values simultaneously. The function zip offers a generalisation of this approach for any multiple data structure that you want to loop through at the same time. For instance, imagine that you have two lists and in the first iteration you need the first value in each of the lists, then the second, and so on. You can simply call for variable_1,variable_2 in zip(list_1,list_2):. The first variable maps to the first entry in the zip function and the second variable to the second entry. You can loop through as many data structures at the same time as you want using this approach, just make sure the number of variables and inputs into zip are the same.

# Define a list of ages
ages = [9, 14, 20, 90]
# Define a list of age groups
age_groups = ['child', 'teenager', 'adult', 'senior']

for age, group in zip(ages, age_groups):
    print("The patient is", age, "years old.")
    print("They are a(n)", group)
The patient is 9 years old.
They are a(n) child
The patient is 14 years old.
They are a(n) teenager
The patient is 20 years old.
They are a(n) adult
The patient is 90 years old.
They are a(n) senior

6.5. Nested Conditionals#

Sometimes you may need to check another condition inside a conditional block. This is called a nested conditional.

In the following example:

  • First we loop through different ages using the for loop

  • Then inside the block we check they are at least 18

for age in range(12, 24, 2):
    print()
    print("The patient is", age, "years old.")

    if age >= 18:
        print("The patient is an adult.")
    else:
        print("The patient is a minor.")
The patient is 12 years old.
The patient is a minor.

The patient is 14 years old.
The patient is a minor.

The patient is 16 years old.
The patient is a minor.

The patient is 18 years old.
The patient is an adult.

The patient is 20 years old.
The patient is an adult.

The patient is 22 years old.
The patient is an adult.

Tip About Readibility

Avoid nesting too many conditionals inside each other.
Deeply nested code can become hard to read.
Sometimes it is better to reorganise your conditions to keep your code clean and understandable.

6.6. Stopping loops#

Sometimes you want your loops to stop prematurely. For this you can use the break and continue statements. Break fully stops the loop and moves on to the next code block. In contrast, continue stops the current iteration and moves on to the start of the loop for the next iteration step. These statements are very useful in combination with if-statements and when you might get stuck in an infinite loop. Compare the two examples that only differ in whether we use break or continue to better understand their difference:

# Using a break statement to stop the loop
for age in range(12, 24, 2):
    print()
    print("The patient is", age, "years old.")

    if age >= 18:
        break # Stop the loop here

    print("The patient is a minor.")

print()
print("Finished iterating over the ages.")
The patient is 12 years old.
The patient is a minor.

The patient is 14 years old.
The patient is a minor.

The patient is 16 years old.
The patient is a minor.

The patient is 18 years old.

Finished iterating over the ages.
# Using a continue statement to stop the loop (iteration)
for age in range(12, 24, 2):
    print()
    print("The patient is", age, "years old.")

    if age >= 18:
        continue # Stop the current iteration and move on to the next one

    print("The patient is a minor.") # this line is skipped if age >= 18

print()
print("Finished iterating over the ages.")
The patient is 12 years old.
The patient is a minor.

The patient is 14 years old.
The patient is a minor.

The patient is 16 years old.
The patient is a minor.

The patient is 18 years old.

The patient is 20 years old.

The patient is 22 years old.

Finished iterating over the ages.

6.7. Quick Practice#

Try this combined challenge:

  • Create a variable temperature with a value of your choice.

  • Write an if-elif-else block:

    • Print "It's cold!" if the temperature is below 10 degrees.

    • Print "It's moderate!" if the temperature is between 10 and 20 degrees (inclusive).

    • Otherwise, print "It's warm!".

  • Add nested conditionals:

    • Inside the "It's warm!" block, check if the temperature is greater than 30 degrees.

      • If so, print an additional message: "It's hot!".

    • Put the whole if-elif-else block inside a while loop:

      • Set a maximum temperature (greater than 30) that your temperature should get to in the conditional statement

      • After the if blocks at the end (but still inside) the while block update the temperature by 5 degrees plus

# Put your code here
šŸ’” Solution
temperature = 9

while temperature < 40:
    if temperature < 10:
        print("It's cold!")
    elif temperature <= 20:
        print("It's moderate!")
    else:
        print("It's warm!")
        if temperature > 30:
            print("It's hot!")
    
    temperature = temperature + 5
    print("The temperature is now", temperature)