Basic math in Python#

With our understanding of variables, methods, and functions, we’ll have a look at how to do some basic math in Python. Besides the available operators in Python, we will also make use of modules from the Python standard library.

First, we define the variables a and b again and assign the values 5 and 3:

a = 5
b = 3

Usage of mathematical operators and built-in functions#

To do math with variables, we can combine them with mathematical operators.

c = a + b # add
d = a - b # subtract
e = a * b # multiply
f = a ** b # exponent
g = a / b # divide
h = a // b # rounding division
i = a % b # modulo
print(c)
8

We can also use built-in functions for math:

pow(a, b)
125
abs(-1)
1
round(1.6)
2

Sometimes, functions may behave unexpected:

round(4.5)
4
round(5.5)
6
round(6.5)
6

So always test those functions before productive use and refer to the official docs

Usage of modules#

Modules can be used for additional mathematical functionalities, e.g., the math module or the statistics module. To do so, they need to be imported before:

import math
import statistics
math.ceil(6.5)
7
math.floor(6.5)
6
math.sqrt(9)
3.0
math.pi
3.141592653589793
data = [3, 5, 1, 7, 2, 1]
statistics.mean(data)
3.1666666666666665
statistics.mode(data)
1

Exercise#

With our knowledge about the built-in functions, how can we compute the mean value of the following list, without using statistics.mean()?

my_list = [1, 2, 3, 4, 5]