⇦ Back

1 Arithmetic

All the usual mathematical operations can be done in Python:

# Addition and subtraction
print(4 + 5 - 2)
## 7
# Multiplication and division
# (works left-to-right, as per BODMAS)
print(2 * 100 / 4)
## 50.0
# Raising to a power
print(2**4)
## 16
# Integer division
# (floor division)
print(47 // 5)
## 9
# Modulus
print(13 % 5)
## 3

2 Functions

For more complicated operations there are functions to do it for you. Many of these can be found in the Numpy package:

import numpy as np

# Square root
print(np.sqrt(49))
## 7.0
# Round down
print(np.floor(-6.28318531))
## -7.0
# Round up
print(np.ceil(-6.28318531))
## -6.0
# Round to a certain number of decimal places
print(round(-6.28318531, 3))
## -6.283
# Round to a certain multiple of 10
print(round(-6283.18531, -2))
## -6300.0
# Absolute value
print(abs(-6.28318531))
## 6.28318531

In order to do more aesthetic changes such as removing trailing zeros or rounding to significant digits, see the page on formatted strings.

3 Constants

The math package gives you access to three mathematical constants:

import math

print(math.pi)
## 3.141592653589793
print(math.tau)
## 6.283185307179586
print(math.e)
## 2.718281828459045

4 Random Numbers

You can generate random numbers using the random package:

import random

# A random number between 50 and -50
print(random.randint(-50, 50))
## 32

Of course, when you generate a random number like this it will (probably) be different each time you run your code. This is unhelpful if you’re trying to write an example or a script where you want the output to be consistent and re-producible. Fortunately, you can generate the same random number each time you run your script by setting the seed of the random number generator (if you don’t set the seed, Python uses the current system time of your computer):

random.seed(1234)

# A random number between 50 and -50 (specifically, it will be 49)
print(random.randint(-50, 50))
## 49

⇦ Back