3.3 Math

3.3.1 Mathematical operations

A lot of mathematical operations in Python are straightforward. Here are some of the basic operations we can perform:

  • + and -: addition and subtraction
  • * and /: multiplication and division
  • **: exponentials

We can perform mathematical operations on values directly:

print(2 + 3)
## 5

Or we can operate on variables:

myValue = 4 
print(myValue**2)
## 16

Python will automatically convert integers to floats when appropriate:

print(3 + 2.2)
## 5.2

We can save the output of an expression as a variable:

my_product = 2 * 10
print(my_product)
## 20

And likewise we can perform mathematical operations on variables, if these variables store numeric data:

number1 = 7
print(number1 / 2)
## 3.5

3.3.2 Order of operations

Python follows the usual mathematical order of operations. And like in math, we can use parentheses () to enforce a specific order.

print(2 * (2 + 2))
## 8