18  If statements

Author

Andres Patrignani

Published

January 6, 2024

if statements control the flow of a program by evaluating whether a certain condition is true or false, and then executing specific actions based on that evaluation. The core syntax of an if statement involves specifying a condition and an action to be executed if that condition is true.

Syntax

if condition:
    # Code block executes if condition is true
elif another_condition:
    # Code block executes if another condition is true
else:
    # Code block executes if none of the above conditions are true

Example 1: Soil pH

Soil pH is a measure of soil acidity or alkalinity. The pH scale ranges from 0 to 14, with a pH of 7 considered neutral. Acidic soils have pH values below 7, indicating an abundance of hydrogen ions (H+), while alkaline soils have pH values above 7, indicating an excess of hydroxide ions (OH-). Soil pH plays a vital role in nutrient availability to plants, microbial activity, and soil structure.

pH = 7  # Soil pH

if pH >= 0 and pH < 7:
    soil_class = 'Acidic'
elif pH == 7:
    soil_class = 'Neutral'
elif pH > 7 and pH <= 14:
    soil_class = 'Alkaline'
else:
    soil_class = 'pH value out of range.'

print(soil_class)
Neutral

Example 2: Saline, sodic, and soline-sodic soils

For instance, in soil science we can use if statements to categorize soils into saline, saline-sodic, or sodic based on electrical conductivity (EC) and the Sodium Adsorption Ratio (SAR). Sometimes soil pH is also a component of this classification, but to keep it simple we will only use EC and SAR for this example. We can write a program that uses if statements to classify salt-affected soils following this widely-used table:

Soil Type EC SAR
Normal < 4.0 dS/m < 13
Saline ≥ 4.0 dS/m < 13
Sodic < 4.0 dS/m ≥ 13
Saline-Sodic ≥ 4.0 dS/m ≥ 13

Here is a great fact sheet where you can learn more about saline, sodic, and saline-sodic soils

ec = 3 # electrical conductivity in dS/m
sar = 16 # sodium adsorption ratio (dimensionless)

# Determine the category of soil
if (ec >= 4.0) and (sar < 13):
    classification = "Saline"

elif (ec < 4.0) and (sar >= 13):
    classification = "Sodic"

elif (ec >= 4.0) and (sar >= 13):
    classification = "Saline-Sodic"

else:
    classification = "Normal"
    
print(f'Soil is {classification}')
      
Soil is Sodic

Example 3: Climate classification based on aridity index

To understand global climate variations, one useful metric is the Aridity Index (AI), which compares annual precipitation to atmospheric demand. Essentially, a lower AI indicates a drier region:

AI = \frac{P}{PET}

where P is the annual precipitation in mm and PET is the annual cummulative potential evapotranspiration in mm.

Over time, the definition of AI has evolved, leading to various classifications in the literature. Below is a simplified summary of these classifications:

Climate class Value
Hyper-arid 0.03 < AI
Arid 0.03 < AI ≤ 0.20
Semi-arid 0.20 < AI ≤ 0.50
Dry sub-humid 0.50 < AI ≤ 0.65
Sub-humid 0.65 < AI ≤ 0.75
Humid AI > 0.75
# Define annual precipitation and atmospheric demand for a location
P = 1200   # mm per year
PET = 1800 # mm per year

# Compute Aridity Inde
AI = P/PET 

# Find climate class
if AI <= 0.03:
    climate_class = 'Arid'
    
elif AI > 0.03 and AI <= 0.2:
    climate_class = 'Arid'

elif AI > 0.2 and AI <= 0.5:
    climate_class = 'Semi-arid'

elif AI > 0.5 and AI <= 0.65:
    climate_class = 'Dry sub-humid'
    
elif AI > 0.65 and AI <= 0.75:
    climate_class = 'Sub-humid'
    
else:
    climate_class = 'Humid'
    
print('Climate classification for this location is:',climate_class,'(AI='+str(round(AI,2))+')')
Climate classification for this location is: Sub-humid (AI=0.67)

Comparative anatomy of If statements

Python

pH = 7  # Soil pH

if pH >= 0 and pH < 7:
    soil_class = 'Acidic'
elif pH == 7:
    soil_class = 'Neutral'
elif pH > 7 and pH <= 14:
    soil_class = 'Alkaline'
else:
    soil_class = 'pH value out of range.'

print(soil_class)

Matlab

pH = 7; % Soil pH

if pH >= 0 && pH < 7
    soil_class = 'Acidic';
elseif pH == 7
    soil_class = 'Neutral';
elseif pH > 7 && pH <= 14
    soil_class = 'Alkaline';
else
    soil_class = 'pH value out of range.';
end

disp(soil_class)

Julia

pH = 7  # Soil pH

if 0 <= pH < 7
    soil_class = "Acidic"
elseif pH == 7
    soil_class = "Neutral"
elseif 7 < pH <= 14
    soil_class = "Alkaline"
else
    soil_class = "pH value out of range."
end

println(soil_class)

R

pH <- 7  # Soil pH

if (pH >= 0 & pH < 7) {
    soil_class <- "Acidic"
} else if (pH == 7) {
    soil_class <- "Neutral"
} else if (pH > 7 & pH <= 14) {
    soil_class <- "Alkaline"
} else {
    soil_class <- "pH value out of range."
}

print(soil_class)

JavaScript

let pH = 7; // Soil pH

let soil_class;
if (pH >= 0 && pH < 7) {
    soil_class = 'Acidic';
} else if (pH === 7) {
    soil_class = 'Neutral';
} else if (pH > 7 && pH <= 14) {
    soil_class = 'Alkaline';
} else {
    soil_class = 'pH value out of range.';
}

console.log(soil_class);

Commonalities among programming languages:

  • All languages use a conditional if keyword to start the statement.
  • They employ logical conditions (e.g., <, ==, <=) to evaluate true or false.
  • The use of else if or its equivalent for additional conditions.
  • The presence of else to handle cases that don’t meet any if or else if conditions.
  • Block of code under each condition is indented or enclosed (e.g., {} in JavaScript, end in Matlab and Julia).

References

Havlin, J. L., Tisdale, S. L., Nelson, W. L., & Beaton, J. D. (2016). Soil fertility and fertilizers. Pearson Education India.

Spinoni, J., Vogt, J., Naumann, G., Carrao, H. and Barbosa, P., 2015. Towards identifying areas at climatological risk of desertification using the Köppen–Geiger classification and FAO aridity index. International Journal of Climatology, 35(9), pp.2210-2222.

Zhang, H. 2017. Interpreting Soil Salinity Analyses. L-297. Oklahoma Cooperative Extension Service. Link

Zomer, R. J., Xu, J., & Trabucco, A. (2022). Version 3 of the global aridity index and potential evapotranspiration database. Scientific Data, 9(1), 409.