Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Mathematical operators

Learning outcomes

Prerequisites

Mathematical operations on numbers

Before accessing complicated operations, it’s important to learn how to use Python as a simple calculator. There are seven standard mathematical operations that Python can do, though their notation might be slightly different to what you’re used to (e.g. × is written as * in Python):

OperationMathematical NotationPythonic Notation
Additiona+ba + ba + b
Subtractionaba - ba - b
Multiplicationa×ba \times ba * b
Divisiona÷ba \div ba / b
Exponentaba ^ ba ** b
Moduloa mod ba \textrm{ mod } ba % b
Floored Divisiona//ba // ba // b

The modulo and floored division operations may be new to you:

Solution

There could be several solutions, but you could try:

print(97 % 5)
print(97 // 45)

Where 97 = 19 * 5 + 2 and 97 = 45 * 2 + 7.

Python can only perform maths on variables of the data type integer or float. Mathematical operators acted on strings or lists will result in different, exotic, results (more on this later).

A single line of code may have many mathematical operations. In this event, Python will follow the standard order of mathematical operations: you might know this as BODMAS. Use round brackets () when coding your formulas to avoid ambiguity.

Mathematical operators can be used on variables, numbers, or combinations of both. This becomes useful when a number is very long to write or needs to be repeated many times in code. For example, instead of writing out π or Avogadro’s number each time it is used, we can store it at the beginning of the program and only call it by the name you have given it:

pi = 3.141592653589
avogadro = 6.02214e23

# evaluate four times pi times Avogadro's number
product = 4 * pi * avogadro
print(product)

Note that to represent standard form, Python uses the symbol e instead of ×10 n.

Printing mathematical results

There are several ways to display the result of a calculation in Python. As above, we can print a variable, or we could directly evaluate the result inside the print statement, as such:

pi = 3.141592653589
avogadro = 6.02214e23

print(4 * pi * avogadro)

These methods are helpful to obtain a quick result, but if the final presentation is important, we can exert more control over the display of numbers by using more advanced features of the f-string:

mass_C = 12.008 # g mol-1
mass_H = 1.008 # g mol-1
mass_methane = mass_C + 4 * mass_H

# Calling up a variable that has already been calculated
print(f"The mass of methane is {mass_methane:.2f} g mol⁻¹.")
Solution

The syntax :.2f indicates that the number should be given to 2 decimal places.

More information on the formatting codes can be found here.

Solution

Your code should look something like this:

# g mol-1
H = 1.008
C = 12.011
O = 15.999
N = 14.007

print("The mass of ethanol is " , 2 * C + 6 * H + O, "g mol⁻¹." )

mass_cyclohexanone = 6 * C + 10 * H + O
print("The mass of cyclohexanone is " , mass_cyclohexanone, "g mol⁻¹.")

mass_nitrobenzene = 6 * C + H * 5 + N + 2 * O
print(f"The mass of nitrobenzene is {mass_nitrobenzene:.2f} g mol⁻¹.")

You should have got the output:

The mass of ethanol is:  46.069 g mol⁻¹.
The mass of cyclohexanone is:  98.145 g mol⁻¹.
The mass of nitrobenzene is: 123.11 g mol⁻¹.

We only have to define the masses once, and they can be reused for all three sums.

Solution
The numerical answer is 79365.079. For a proposed Python code, keep reading:
# mol L-1
conc_SO2 = 3e-3
conc_O2 = 3.5e-3
conc_SO3 = 5e-2

K_c = conc_SO3**2 / (conc_SO2**2 * conc_O2)

print(f"The equilibrium constant is {K_c:.3f} mol⁻¹ L.")

Mathematical operations on non-numerical data types

Acting mathematical operators on non-numerical data can give surprising results.

Maths on strings and lists

Run the two print statements below.

print("methyl" + "amine")
print("methyl" * 3)

Instead of the mathematical answers 4 and 15, you get this: methylamine and methylmethylmethyl.

In the first example, the two strings have been placed side-by-side. We call this placing concatenation. In the second case, the same string has been concatenated three times.

Addition and multiplication also allows us to concatenate lists:

print([1, 2, 3] + [2, 2, 2])
print([1, 2, 3] * 3)

Which results in [1, 2, 3, 2, 2, 2] and [1, 2, 3, 1, 2, 3, 1, 2, 3].

Type errors

More commonly, operations between numerical and non-numerical data don’t have any built-in meaning. For example:


print("beaker" / 2)

The code above prints a block of text finishing in:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

This is a Python error message. The first part tells us the kind of error that has happened: TypeError. What follows saying that the mathematical operator / has no defined behaviour when combining a string and an integer.

It’s not always easy to decipher Python error message, but fortunately the lines above the error message can help us find the offending line of code. Those lines are called the Traceback.

Solution
In a, the order of operations has been treated poorly, so the answer is incorrect.
In b, the numbers have been turned into strings, and then divided by `3`. Strings can't be divided by integers, which raises `TypeError`.
In c, the strings have been turned into numbers, except Python isn't sure how to turn `"12.0"` into an integer due to the decimal place, even though it is followed by `0`. This raises a new, very common error: `ValueError`.
A simple solution would be:

a = 12.0
b = 5.1
c = 8.5
mean = (a + b + c) / 3
print(mean)

Non-standard mathematical operators

Python has more specialised mathematical operators stored in external pre-written pieces of code called libraries. For example, the math library contains more common mathematical tools, like the square root function sqrt().

To use a function from a library, we must first import it to our program:

import math

print(math.sqrt(16))

Functions from the math library can be accessed by preceding them with math.. We can also bypass this by importing only the function we need, with this syntax:

from math import sqrt

print(sqrt(16))

Finally, some library names are abbreviated by convention (and to save on typing). This is the case for the numpy library, which also has a sqrt function:

import numpy as np
print(np.sqrt(16))

Seeking programming help online

External libraries allow us to complete complex operations by writing few lines of code. In exchange, we need to learn how a library works based on its documentation which can take time. For example, here is the documentation page for numpy.sqrt. There is also authoritative documentation for standard Python, like this section on numeric types.

This kind of documentation is extremely reliable, since it’s written by the authors of the library itself. However, it’s so comprehensive that it can be hard to understand. Another good source for programming answers is Stack Overflow, which pops near the top of many internet searches. Take this page, for example. The top section is a question. Below are answers written by the community and ordered by vote ranking. This means that, even though not every answer is correct, we can dose our trust based on the popularity of the answer, and we can trace back its author.

You may also consider using an AI chatbot to answer your questions. If you do so, you will find that answers to programming questions look extremely similar to the style popularised by Stack Overflow and other such forums for the past few decades. Indeed, Stack Overflow is an influential part of the training set for these chatbots. You might save a bit of time by skipping the online search. In exchange you won’t know the provenance of your answer, and therefore won’t know how much to trust it. As a general guide, if an answer is hard to find by a standard search engine, a chatbot’s answers are more likely to be wrong and made up.

Whatever the source, always check that you understand the code you find before re-using it, and verify the truth of any claims by running some tests on your own computer.

Solution
Two very popular and reliable Python libraries have least‑squares calculators: numpy and scipy.

scipy

Numpy has simpler documentation while scipy has more options. Scroll down both pages to skim the examples of use.

The user “pylang” on Stack Overflow gives a very comprehensive guide. Note that the answer doesn’t just focus on the programming but also on the statistical context of the question, which might be useful.

Summary