Recap that pi is an essential constant when doing mathematical calculations and we can easily access pi using the numpy module in Python. It is simplicity itself:
The output is:
Thus, np.pi is your constant referring to the ratio of a circle’s circumference to its diameter.
You should remember to prefix the “pi” with the module you are taking it from: in our case, numpy. To make your program more readable for yourself, you can do:
Here we are creating a variable (also called “pi”) in our program and initializing it to numpy’s pi. The output is the same:
Calculating the area of a circle
We can use pi in a function that calculates the area of a circle:
Here we are simply writing the formula for the area of a circle in the function area that takes a radius as input. The output prints the radius of a sample circle (7 units) and its area (in units squared):
Calculating the circumference of a circle
Similarly, we can compute the circumference of a circle like so:
The circumference formula simply calculates the diameter times pi to find the length of the circumference. The output is:
Converting degrees to radians
Another use of pi is to convert degrees to radians. Recap that “pi” radians is 180 degrees, so we can write a function like so:
Here we simply multiply the input degrees by pi/180 to obtain the equivalent angle in radians. The output is:
Converting radians to degrees
Similarly we can write the inverse function to convert radians to degrees by simply multiplying the input radians by 180/pi:
The output in the above case will be:
To summarize, pi is an essential constant for geometric calculations and we have easy access to it using Python numpy. Using just one expression (np.pi) we can access its value and use it in any formulaic calculations.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.