Basic math in python#

For understanding how Python works, we will do some basic math using variables and functions. Both play an important role in Python and will accompany us through all chapters.

In the next cell we define a variable called “a” and we assign the value 5 to it.

a = 5

Afterwards, we can re-use this variable, for example to print it out:

print(a)
5

Somtimes, it might be helpful to put some additonal explanatory text when printing out variables:

print("The area is", a)
The area is 5

It shall be highlighted that good scientific practice is also to add physical units.

print("The area is", a, "mm^2")
The area is 5 mm^2

We can use multiple variables and combine them using mathematical operators:

b = 3
c = a + b
print(c)
8
d = 6
e = 7
f = a * d
g = f / e
h = 1 + g
print(h)
5.285714285714286

We can also get the value of a variable or expression (combination of variables) by putting it in a cell alone.

h
5.285714285714286
a + b
8

If you run illegal operations, such a dividing by zero, you receive an error message like this:

a / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Input In [11], in <module>
----> 1 a / 0

ZeroDivisionError: division by zero

If a variable is not defined, you would receive an error message like that:

a / k
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [12], in <module>
----> 1 a / k

NameError: name 'k' is not defined

Built-in math functions#

Python comes with a list of built-in functions

pow(3, 2)
9
abs(-8)
8
round(4.6)
5

Some of these operations are not exactly doing what you expect. Better try them out before you use them.

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

By the way, we can also combine multiple expressions to print out intermediate results in notebooks without wasting too much space.

round(4.5), round(5.5), round(6.5), round(7.5)
(4, 6, 6, 8)

The math library#

There is pre-installed python library of additional math functions. Before you can use them, you need to import this library. Otherwise, you would receive an error like this:

math.sqrt(9)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [21], in <module>
----> 1 math.sqrt(9)

NameError: name 'math' is not defined

When importing a library, you tell the python interpreter that you want to make use of everying that is part of a given library, in our case “math”:

import math

After importing the “math” library, you can use functions that are part of math.

math.sqrt(9)
3.0

Exercise#

Assume you have two points specified by their x and y coordinates. Calculate the Euclidean distance between them.

x1 = 5
y1 = 3

x2 = 8
y2 = 11