This tutorial module surveys some of the basic math functions in Python.
We can perform a mathematical operation on any numeric data type:
5 + 5
> 10
1.2 - 4
> -2.8
4 * 4
> 16
120 / 12.5
> 9.6
Some additional functions include min (minimum) and max (maximum), which return the lowest and highest values in a sequence:
min([0, 5, 2, -4, 1])
> -4
max([10, 20, 30, 40, 50])
> 50
You can use len to find the length of a list:
len([0, 1, 2, 3, 4, 5, 6])
> 7
Further functions include abs (absolute value), % (modulo), and pow (exponentiation):
abs(-17)
> 17
60 % 12
> 0
pow(2, 3)
> 8
Use parentheses to define order of operations:
(1 + 23) % 12
> 0
1 + 23 % 12
> 12
Any of these operations can be conducted on numeric variables:
a = 2
b = 3
a + b
> 5
Or on individual numeric elements of a list (remember that index numbers count from zero and should be placed in brackets):
my_list = [5, 3, 9, 7]
my_list[2] / my_list[1]
> 3.0
Just be aware that lists themselves do not respond to mathematical operations in the same way:
my_list + my_list
> [5, 3, 9, 7, 5, 3, 9, 7]
In order to perform operations with lists, consider using a for loop to iterate over the elements in the list.
For more, check out the w3schools page on math in Python.