Basic Math (Python)

From Linewaves
Jump to navigation Jump to search

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

Returns:

10

Or:

1.2 - 4

Returns:

-2.8

Or:

4 * 4

Returns:

16

Or:

120 / 12.5

Returns:

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])

Gives us:

-4

And:

max([10, 20, 30, 40, 50])

Returns:

50

You can use len to find the length of a list:

len([0, 1, 2, 3, 4, 5, 6])

Returns:

7

Further functions include abs (absolute value), % (modulo), and pow (exponentiation):

abs(-17)

17

Or:

60 % 12

0

Or:

pow(2, 3)

8

Use parentheses to define order of operations:

(1 + 23) % 12

Gives:

0

But:

1 + 23 % 12

Gives:

12

Any of these operations can be conducted on numeric variables:

a = 2

b = 3

a + b

Gives:

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]

Returns:

3.0

Just be aware that lists themselves do not respond to mathematical operations in the same way:

my_list + my_list

Returns:

[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.