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:
= 4
myValue 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:
= 2 * 10
my_product print(my_product)
## 20
And likewise we can perform mathematical operations on variables, if these variables store numeric data:
= 7
number1 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