Python Mathematics

In this topic, we will learn about the mathematical operations supported in Python. 

Python provides modules like math and random to perform mathematical operations related to trigonometry, logarithms, probability, statistics etc.. 

Python math module

The following example shows the math module: 

import math

# Output: 3.141592653589793
print(math.radians(180))

# Output: 25.0
print(math.sqrt(625))

# Output: 3.141592653589793
print(math.pi)

# Output: -1.0
print(math.cos(math.pi))

# Output: 22026.465794806718
print(math.exp(10))

# Output: 3.0
print(math.log10(1000))

# Output: 1.1752011936438014
print(math.sinh(1))

# Output: 5040
print(math.factorial(7))

# Output: 512.0
print(math.pow(8, 3))

 

Python random module

The following example shows the random module: 

import random

# Gives a number between 20 and 30
print(random.randrange(20,30))

x = ['a', 'b', 'c', 'd', 'e', 'f']

# Get random choice
print(random.choice(x))

# Shuffle x
random.shuffle(x)

# Print the shuffled x
print(x)

# Print random element
print(random.random())

Output:

25
f
['e', 'c', 'd', 'b', 'f', 'a']
0.02147812541872285