In this lesson we will study some functions of the Python Math module, to be able to use it in some exercises.
The math module allows you to use some functions such as square root, factorial, logarithm, etc. It is also possible to refer to some constants such as math.pi.
So, to view all the functions that the math module makes available, simply type the help command (‘math’) in interactive mode.
In the figure below I show you some of the mathematical functions.
So, try typing the help function (‘math’) in order to view them all.
Using the Math module in Python
Let’s now make an example of using the math module.
To create the algorithm, I first need to take the two data as input. After taking the hypotenuse and one cathetus as input, as required by the problem, I can, through the Pythagorean theorem, calculate the other cathetus.
So, in this case, we will need the sqrt function, which represents the square root, to calculate the other cathetus.
But, before we can use it, we need to import the module using the import math command.
''' area calculation of a right triangle taking as input a cathetus and the hypotenuse ''' import math #dati in input cathetus = int(input('Insert a cathetus:')) hypotenuse = int(input('Insert hypotenuse:')) #calculation of the other cathetus cathetus_2 = math.sqrt(pow(hypotenuse,2) - pow(cathetus,2)) #calculation and display of the area area = cathetus * cathetus_2/2 print('The area of the triangle is: ', area)
Note that the pow function can also be used without including the math module.
Second example Math module in Python
Let’s go back to the example of the area of the circle considering the constant math.pi.
import math radius = float(input('Insert radius:')) area = math.pi * radius * radius print('The area of the circle of radius ', raggio, ' is:', area)
I could also have written:
area = math.pi * pow (radius, 2)
area = math.pi * radius ** 2
In this lesson we have seen some examples of the Math module in Python. In the next lessons we will see many other exercises related to this important Python module.