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.

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

a = 5
b = 3

Like already shown in 02_basic_terms_and_types, we can reuse the variables, for example, to print their and add more information using an f-string:

print(f"The area is {a} mm^2")
The area is 5 mm^2

Usage of mathematical operators and built-in functions#

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

Also see the available operators in Python.

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(f)
125

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
round(7.5)
8

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.sqrt(9)
3.0
math.pi
3.141592653589793
data = [3, 5, 1, 7, 2, 1]
statistics.mean(data)
3.1666666666666665
statistics.mode(data)
1