12  Basic operations

Author

Andres Patrignani

Published

January 5, 2024

We start our Python journey with the most traditional step in learning any programming language: writing a “Hello World” program. This simple exercise is a rite of passage for all new programmers. It involves writing a short piece of code that displays the phrase “Hello World” on the screen. While it might seem elementary, this exercise is crucial as it introduces you to the basic structure of a Python program and the process of executing code. It’s your first step into the world of coding, where you begin to understand how a few lines of code can create an output, setting the stage for more complex and exciting projects ahead.

Below we will cover the following concepts:

Tip

Press the Ctrl + Enter keys to run code in a cell. You can also press the Ctrl + Shift + Enter keys to run code in a cell and move onto the next cell.

Hello World

# The most iconic line of code when learning how to program
print("Hello World")
Hello World

Comments

In Python, as in any programming language, comments play a crucial role in enhancing the clarity, readability, and maintainability of code. Comments are used to annotate various parts of the code to provide context or explain the purpose of specific blocks or lines. This is especially important in Python, where the emphasis on clean and readable code aligns with the language’s philosophy. Comments are a mark of good programming practice and help both the original author and other programmers who may work with the code in the future to quickly understand the intentions, logic, and functionality of the code.

In Python, a comment is created by placing the hash symbol # (a.k.a. pound sign, number sign, sharp, or octothorpe) before any text or number. Anything following the # on the same line is ignored by the Python interpreter, allowing programmers to include notes and explanations directly in their code.

# This line is a comment and will be ignored by the Python interpreter.
print("This sentence will print") # This sentence will not print
This sentence will print
Tip

Comments can be used to disable code lines without deleting them. This is especially handy when experimenting with different solutions. You can retain alternative code snippets as comments, which will be ignored by the interpreter, but remain available for reference or reactivation at a later time.

Arithmetic operations

In Python, arithmetic operators are fundamental tools used for performing basic mathematical operations. The most commonly used operators include addition (+), subtraction (-), multiplication (*), and division (/). Apart from these, Python also features the modulus operator (%) which returns the remainder of a division, the exponentiation operator (**) for raising a number to the power of another, and the floor division operator (//) which divides and rounds down to the nearest whole number. These operators are essential building blocks and form the basis of more complex mathematical functionality in the language.

print(11 + 2)   # Addition
print(11 - 2)   # Subtraction
print(11 * 2)   # Multiplication
print(11 / 2)   # Division
print(11 // 2) # Floor division
print(11**2)    # Exponentiation
print(11 % 2)  # Modulus
13
9
22
5.5
5
121
1
Tip

In newer versions of Jupyter Lab you can run a single line of code within a cell using Run Selected Text or Current Line in Console in the Run menu.

Exponentiation

In Python, the exponentiation operation is performed using a double asterisk (**), which is a departure from some other programming languages, such as Matlab, where a caret (^) is used for this operation.

Simple computations

In programming, a variable is like a storage box where you can keep data that you might want to use later in your code. Think of it as a named cell in an Excel spreadsheet. Just as you might store a number or a piece of text in a spreadsheet cell and refer to it by its cell address (like A1 or B2), in coding, you store data in a variable and refer to it by the name you have given it. Variables are essential because they allow us to handle data dynamically and efficiently in our programs.

To get comfortable with the language syntax, variable definition, data types, and operators let’s use Python to solve simple problems that we typically carry on a calculator. In the following examples you learn how to:

  • code and solve a simple arithmetic problem
  • document a notebook using Markdown syntax
  • embed LaTeX equations in the documentation

Example 1: Unit conversions

Perhaps one of the most common uses of calculators is to do unit conversions. In this brief example we will use Python to conver from degrees Fahrenheit to degrees Celsius:

C = (F-32) \frac{5}{9}

Note

Always assign meaningful names to your variables. Variable names must start with a letter or an underscore and cannot contain spaces. Numbers can be included in variables names as long as they are preceded by a letter or underscore.

value_in_fahrenheit = 45
value_in_celsius = (value_in_fahrenheit-32) * 5/9

# Print answer
print("The temperature is:", round(value_in_celsius,2), "°C")
The temperature is: 7.22 °C
Help access

The print and round functions can take multiple arguments as inputs. In this context, the comma is a delimiter between the function inputs. Use the help() or ? command to access a brief version of the documentation of a function. For instance, both help(round) and round? will print the documentation for the round() function, showing the the first argument is the number we want to round, and the second argument is the number of decimal digits. The official documentation for the round() function is available at this link.

# Access functon help
round?
Signature: round(number, ndigits=None)
Docstring:
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None.  Otherwise
the return value has the same type as the number.  ndigits may be negative.
Type:      builtin_function_or_method
# Find current variables in workspace
%whos
Variable              Type     Data/Info
----------------------------------------
value_in_celsius      float    7.222222222222222
value_in_fahrenheit   int      45

Example 2: Compute the hypotenuse

Given that a and b are the sides of a right-angled triangle, let’s compute the hypotenuse c. For instance, if a = 3.0 and b = 4.0, then our code must return a value of c = 5.0 since:

c = \sqrt{a^2 + b^2}

a = 3.0 # value in cm
b = 4.0 # value in cm
hypotenuse = (a**2 + b**2)**(1/2)

# Print answer
print('The hypotenuse is:', round(hypotenuse, 2), 'cm')
The hypotenuse is: 5.0 cm

Did you notice that we used **(1/2) to represent the square root? Another alternative is to import the math module, which is part of the Python Standard Library, and extends the functionality of our program. To learn more, check the notebook about importing Python modules.

import math
hypotenuse = math.sqrt((a**2 + b**2))

# Print answer
print('The hypotenuse is:', round(hypotenuse, 2), 'cm')
The hypotenuse is: 5.0 cm
# The math module also has a built-in function to compute the Euclidean norm or hypothenuse
print(math.hypot(a, b))
5.0

Example 3: Calculate soil pH

Soil pH represents the H^+ concentration in the soil solution and indicates the level of acidity or alkalinity of the soil. It is defined on a scale of 0 to 14, with pH of 7 representing neutral conditions, values below 7 indicating acidity, and values above 7 indicating alkalinity. Soil pH influences the availability of nutrients to plants and affects soil microbial activity. It is typically measured using a pH meter or indicator paper strips, where soil samples are mixed with a distilled water and then tested.

The formula is: pH = -log_{10}(H^+)

H_concentration = 0.0001
soil_ph = -math.log10(H_concentration)
print(soil_ph)
4.0

Example 4: Calculate bulk density

The bulk density is crucial soil physical property for understanding soil compaction and soil health. Assume that an undisturbed soil sample was collected using a ring with a diameter of 7.5 cm and a height of 5.0 cm. The soil was then oven-dried to remove all the water. Given a mass of dry soil (M_s) of 320 grams (excluding the mass of the ring), calculate the bulk density (\rho_b) of the soil using the following formula: \rho_b = M_s/V. In this case we assume that the ring was full of soil, so the volume of the ring is the volume of the soil under analysis.

dry_soil = 320 # grams
ring_diamter = 7.5 # cm
ring_height = 5.0 # cm
ring_volume = math.pi * (ring_diamter/2)**2 * ring_height # cm^3

bulk_density = dry_soil/ring_volume

# Print answer
print('Bulk density =', round(bulk_density, 2), 'g/cm³')
Bulk density = 1.45 g/cm³
Tip

In Python 3, UTF-8 is the default character encoding, so Unicode characters can be used anywhere. This is why we can write °C and cm³. Here is an extensive list of Unicode characters

Example 5: Compute grain yield

Computing grain yield is probably one of the most common operations in the field of agronomy. In this example we will compute the grain yield for a corn field based on kernels per ear, the number of ears per plant, the number of plants per square meter, and the weight of 1,000 kernels. This example can be easily adapted to estimate the harvestable yield of other crops.

# Define variables
kernels_per_ear = 500
ears_per_plant = 1
plants_per_m2 = 8
weight_per_1000_kernels = 285 # in grams

# Calculate total kernels per square meter
kernels_per_m2 = kernels_per_ear * ears_per_plant * plants_per_m2

# Calculate yield in grams per square meter 
# We divide by 1000 to compute groups of 1000 kernels
yield_g_per_m2 = (kernels_per_m2 / 1000) * weight_per_1000_kernels

# Convert yield to kilograms per hectare 
# Use (1 hectare = 10,000 square meters) and (1 metric ton = 1 Mg = 1,000,000 g)
yield_tons_per_ha = yield_g_per_m2 * 10000 / 10**6

print("Corn grain yield in metric tons per hectare is:", yield_tons_per_ha)
Corn grain yield in metric tons per hectare is: 11.4

Python is synchronous

An important concept demonstrated by the time module is Python’s synchronous nature. The Python interpreter processes code line by line, only moving to the next line after the current one has completed execution. This sequential execution means that if a line of code requires significant time to run, the rest of the code must wait its turn. While this can cause delays, it also simplifies coding by allowing for a straightforward, logical sequence in scripting. With the sleep() method, we can introduce a time delay to simulate extended computations.

print('Executing step 1')
time.sleep(5)  # in seconds

print('Executing step 2')
time.sleep(3)  # in seconds

print('Executed step 3')

print('See, Python is synchronous!')
Executing step 1
Executing step 2
Executed step 3
See, Python is synchronous!

Practice

Create a notebook that solves the following problems. Make sure to document your notebook using Markdown and LaTeX.

  1. Convert 34 acres to hectares. Answer: 13.75 hectares

  2. Compute the slope (expressed as a percentage) between two points on a terrain that are 150 meters apart and have a difference in elevation of 12 meters. Answer: 8% slope

  3. Compute the time that it takes for a beam of sunlight to reach our planet. The Earth-Sun distance is 149,597,870 km and the speed of light in vacuum is 300,000 km per second. Express your answer in minutes and seconds. Answer: 8 minutes and 19 seconds

Syntax tip

Code readability is a core priority of the Python language. Since Python 3.6, now we can use underscores to make large numbers more readable. For instance, the distance to the sun could be written in Python as: 149_597_870. The Python interpreter will ignore the underscores at the time of performing computations.