Kodeclik Blog


Pi in Python numpy

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.
Write to us to tell us how you used numpy.pi()!
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.