Conditional Statements#

Learning Outcomes#

  • To build statements and scripts that can do different tasks when given different inputs.

  • To use comparison operators in if statements.

Prerequisites#

‘if’ statements#

For most real programs we want certain actions to be performed only when specific conditions are met. For example, we want to record a data point only if it has an uncertainty within acceptable tolerance, or only if it is above baseline noise. We use comparisons and logic to establish those conditions.

To ensure an action is only executed under a certain condition, we use if statements. These require a specific syntax.

if condition:
   what to do if condition is True

When the condition is True, Python will go on to run the code which is indented. Indentation is how Python knows what is part of the if statement, and what is the rest of the code. Often, programs in which you write Python will automatically insert indentation after the if condition: (not forgetting the colon!), but you can also use the ‘tab’ key to insert the correct indentation (which as a standard is 4 spaces). If there is no colon and no indentation, errors can occur.

If the condition is False, the indented code is ignored, and Python continues onto whatever the next non-indented lines are.

Using if

The main way we can use if statements is in conjunction with comparisons.

x = "CH4"
y = "CH4"
if x == y:
    # This part of the code is indented, and is run only if the if statement is true
    print("Yes, these are the same formula")

Running this code, we get the output Yes, these are the same formula. If we were to then change one of the variables:

x = "CH4"
y = "NH3"
if x == y:
    print("Yes, these are the same formula")
print("The indentation has ended, this code line is always run")

The code skips straight to the new line and prints only the second statement. This is because x == y is False.


Exercise: Write a simple 'if' statement

A nickel surface has workfunction 5.08 eV. If a photon incident on the surface has energy greater or equal to this energy, an electron will be liberated from the surface. Write a conditional (‘if’) statement to test if a photon of energy 6.17 eV will liberate an electron, and print the energy, and a sentence explaining if an electron has been released.

Click to view answer
workfunction_Ni = 5.08 # eV
photon_energy = 6.17 # eV

if photon_energy >= workfunction_Ni:
    print(f"The photon has energy {photon_energy} eV, and will release an electron from the nickel surface")

Don’t forget the colon after the conditional statement, and to indent the print() line.


If…elif…else#

What if we want to have multiple different categories and multiple different outcomes? We can use if... else if we want to do one thing if a statement is true, and then something else for all other possibilities.

if condition:
   what to do if condition is True
else:
   what to do if condition is False

Alternatively, if we have more than two decisions to make, we can use if... elif... else, with elif statements acting like further ‘if’ statements that are only checked if all the statements above are False. Elif is short for ‘else if’, and will only be checked if the condition above is not met. For example:

if condition:
   what to do if condition is True
elif other_condition:
   what to do if previous conditions are False, but this condition is True
else final_condition:
   what to do if all previous conditions are False


Note!
You can put in as many conditions as you like, but be careful, conditional statements are strictly ordered. If the first if block is True, only that code block will run, and further elif statements are ignored, even if they would be True!

Using if...else...

We can use if…else… when we have only two outcomes we want to test.

x = "CH4"
if x == "CH4":
    print("This compound is methane")
else:
    print("This compound is not methane")

Understanding if...elif...else... logic

When writing ‘if…elif…’ statements, it is important to remember that once a conditional statement has returned true, no further elif or else statements will be tested.

This is demonstrated in the code below:

wavelength = 4.82e-8

if wavelength < 1e-11:
    print("This is a gamma wave")
elif wavelength < 1e-8:
    print("This is an x-ray")
elif wavelength < 3.8e-7:
    print("This is a UV ray")
elif wavelength < 7.4e-7:
    print("This is in the visible range")
elif wavelength < 1e-3:
    print("This is infrared")
else:
    print("This is a radiowave")

The output is:
This is a UV ray

Even though all comparisons after “This is a UV ray” are also True, no other statements are printed. If you wanted to test every single comparison, you would have to use multiple if statements.


Exercise: Predict if...elif...else logic

Look at each of the code snippets below and for each, predict which print() statements will execute. Write them out yourself and check you were correct.

a)

x = "CH4"
if x == "CH4":
   print("This compound is methane")
elif x != "NH3":
   print("This compound is not ammonia")
else:
   print("This compound is ammonia")

b)

x = "H2O"
if x == "CH4":
   print("This compound is methane")
elif x != "NH3":
   print("This compound is not ammonia")
elif x != "H2":
   print("This compound is not hydrogen")
else:
   print("This compound is ammonia")

c)

x = "H2"
if x != "H2O":
   print("This compound is not water")
if x == "H2":
   print("This molecule is hydrogen")
else:
   print("This compound is not hydrogen")
Click to view answer
a) Only the first print() statement is executed. Even though the `elif` statement is also True, this is not executed because the first condition has already been met.

b) The first if condition is False, so the program moved on to check the elif statement. The first elif statement is True, so that print() statement is executed, but the second elif statement and the else statement are ignored.

c) Two if statements are being used instead of a following elif. This means that both conditions are checked, even if the first one is True. Therefore, both statements are executed.


Visualising if statements using flowcharts#

if statements can be complex, and abstract. They can be visualised using a flowchart.

If statements can be summarised by the following flowchart:

if-statements-flowchart

You can see that if the first statement is True, the code completely skips the elif and else statements, which are not checked.

Further Practice#

Question 1#

When doing IR spectroscopy, a peak with low % transmittance corresponds to a strong spike on the spectrum (the compound strongly absorbing light). When analysing a particular spectrum, any peaks with transmittance greater than 95% are indistinguishable from background noise, and are ignored.

Write a Python conditional statement that will print whether our peak is background noise or not.

Click to view answer
peak_frequency = 3200 # cm-1
peak_transmittance = 97 # %

if peak_transmittance >= 95 and peak_transmittance <= 100:
    print(f"The peak at {peak_frequency} cm-1 has an absorbance of {peak_transmittance}% and can be considered background noise.")
elif peak_transmittance < 0 or peak_transmittance >100:
    print("Peak absorbance cannot be less than zero or greater than 100. There may be an error in your instrument.")
else:
    print(f"The peak at {peak_frequency} cm-1 has an absorbance of {peak_transmittance}%")

Question 2#

Using your code to calculate the pH of a solution from concentration of H+ ions (from the mathematical operators lesson, example shown below), add an if statement which will print whether the pH is basic, acidic, or a superacid (pH < 0 ). Test for each of the following values of H_conc:

H_conc = 1.0e-10
H_conc = 1.0e-7
H_conc = 1.0e-3
H_conc = 1.0e12

# Calculate pH of a solution from [H+]
H_conc = 1.0e12

pH = log10(H_conc)
pH *= -1

print(pH)
Click to view answer

Below is a possible answer. Note that since this is done from superacid upwards, the first elif statement does not need the addition of elif pH > 0 and pH < 7:, since it will only run if pH <= 0 is False. However, if you were working from base downwards, you would have to specify that pH must be both larger than 0 and smaller than 7 to be marked as acidic.

from math import log10

# Defining the initial concentration
# Change this value to test your 'if' statements are correct
H_conc_1 = 1.0e-10
H_conc_2 = 1.0e-7
H_conc_3 = 1.0e-3
H_conc_4 = 1.0e12

pH = log10(H_conc_1)
pH *= -1

# It is good to print your answer to check it is what you are expecting
print(f"The pH of this solution is: {pH}")

# Checks pH and assigns it 'superacid', 'acidic', 'neutral', or 'basic'
if pH <= 0:
    print("This solution is a superacid")
elif pH < 7:
    print("This solution is acidic")
elif pH == 7:
    print("This solution is neutral")
elif pH > 7:
    print("This solution is basic")

Think further . This program contains 4 values for the concentration of H+ ions, but can only check one at a time. This is quite slow. A better way would be to use loops iterate through all four values and output the desired phrase for them all at the same time, removing the laborious task of changing the value for the concentration manually. We will learn about loops in the next few lessons.


Learning Outcomes#

  • How to use if...elif...else statements to do certain tasks only if certain comparisons or statements are the case.

  • Utilising comparisons in if statements.

Summary of learning#

  • if...elif...else is used to create code that only executes if a certain condition is met.

  • Syntax is important. Use a colon after every if/elif/else condition, and indent any following code that should execute if that condition is met.

  • When an if statement is True, elif and else statements directly following it will not execute.

  • Use multiple if statements if you want every statement checked. Consider how you can minimise the number of if statements to have a more efficient and less cluttered code.

  • Use flowcharts to visualise your conditional statements.