Python as a calculator

4.3. Python as a calculator#

Python has a set of mathematical functions that are built directly into the language. You can, therefore, use Python as a calculator.

1+1

Calculations also work with variables:

a = 5
print(a+1)

Exercise 4.5

Discover what the following Python operators do by performing some math with them in the code cell below: *, -, /, **, //, %. Use print to investigate the outputs.

# Your code here

Integer division (//) and modulus (%) operators

The integer division operator // performs division and truncates the decimal part to return the largest integer less than or equal to the result.

The modulus operator % gives the remainder when one number is divided by another.

For example, if we divide 13 by 3, the result is 4.333. Therefore, the largest integer less than the resulting 4.333 is 4 and the remainder is 1. If you think in the opposite direction, you could “construct” number 13 as 3*4 + 1. Therefore, in Python the result of 13 // 3 would be 4, and the result of 13 % 3 would be 1.

Another handy built-in function is abs() for calculating absolute values:

print(abs(10))
print(abs(-10))
print(abs(1j))
print(abs(1+1j))

You can find the full list of built-in mathematical commands on the Python documentation webpage.