Area of Circle in Python: Program Guide with math.pi
Three Python programs to calculate circle area: hardcoded π, math.pi, and numpy.pi. Covers input handling, edge cases, and verified outputs for r=5.
The formula for a circle’s area in Python is math.pi * r**2, and the π constant you choose shapes every decimal place in the output.
Three approaches exist: hardcoding π as 3.14, using math.pi, and using numpy.pi for array operations. This guide covers all three, plus user-input handling, edge cases, and two real-world extensions.
The Formula: πr²
The area of a circle is A = π × r², where r is the radius. The constant π (pi) is the ratio of a circle’s circumference to its diameter; that same ratio scales when you fill in the disc, giving the familiar area formula.
In Python, radius ** 2 computes r² using the exponentiation operator, and multiplying by π gives the area. If r is in centimetres, the result is in cm².
import math
radius = 5.0
area = math.pi * radius ** 2
print(area) # 78.53981633974483
Three Python Implementations
All three methods produce a float result. What differs is the π value used and whether the structure targets a single value or an array.
Hardcoded π: Simpler but Less Precise
PI = 3.14
radius = float(input("Enter the radius: "))
area = PI * radius ** 2
print(f"Area = {area:.2f}")
Sample outputs:
radius = 3→Area = 28.26radius = 8→Area = 200.96
The value 3.14 is close to true π but not exact. For placement coding tests where the judge compares output against a math.pi-based reference answer, the minor difference will produce a wrong-answer verdict. Classroom exercises that only check rough correctness are generally unaffected.
Using 3.14159 narrows the gap, but math.pi is accurate to IEEE 754 double precision and there is no reason to type out digits manually.
math.pi: The Standard Approach
The math module exports math.pi = 3.141592653589793, accurate to 15 significant figures:
import math
radius = float(input("Enter the radius: "))
area = math.pi * radius ** 2
print(f"Area = {area:.4f}")
Sample outputs:
radius = 5→Area = 78.5398radius = 6→Area = 113.0973
This is the preferred approach for standalone calculations. math.pi is a regular Python float, so no type conversion happens when you multiply it against another float.
numpy.pi: For Array Contexts
When radii are stored in a NumPy array (common in data-science preprocessing), use numpy.pi so that π broadcasts correctly across every element:
import numpy as np
radii = np.array([1.0, 2.0, 3.0, 5.0, 7.0])
areas = np.pi * radii ** 2
print(areas.round(4))
# [ 3.1416 12.5664 28.2743 78.5398 153.938 ]
numpy.pi and math.pi hold the same numeric value (3.141592653589793). The difference is context: in a NumPy expression, np.pi broadcasts correctly and signals that the code was written for array use.
User Input and Type Conversion
Reading the radius from keyboard input:
radius = float(input("Enter the radius: "))
Use float(), not int(). A radius of 5.5 is geometrically valid; int("5.5") raises a ValueError because "5.5" is not a whole-number string. float("5") converts an integer string correctly, so float() handles both cases without extra logic.
To guard against non-numeric input:
import math
try:
radius = float(input("Enter the radius: "))
except ValueError:
print("Invalid input. Please enter a numeric value.")
radius = None
if radius is not None:
area = math.pi * radius ** 2
print(f"Area = {area:.4f}")
The try/except block catches anything float() cannot convert (an empty string, "abc") and gives the user a clear message instead of a Python traceback.
Formatted Output with f-strings
Python 3.6+ f-strings give the cleanest control over decimal places:
area = math.pi * 5 ** 2 # 78.53981633974483
print(f"Area = {area:.2f}") # Area = 78.54
print(f"Area = {area:.4f}") # Area = 78.5398
The .2f format specifier means: print as a fixed-point float with 2 decimal places. Changing .2f to .4f gives 4 decimal places.
The older %-formatting still works and appears in legacy code:
print("%.2f" % area) # 78.54
Both produce the same numeric output. f-strings are preferred in code written for Python 3.6 and later; they are faster, more readable, and handle expressions without a separate variable.
Edge Cases: Zero and Negative Radius
Two inputs need explicit consideration:
- Zero radius:
math.pi * 0 ** 2evaluates to0.0. A circle of radius zero has zero area; the formula handles this correctly without any guard. - Negative radius: Python evaluates
(-3) ** 2as9(correct arithmetic), somath.pi * (-3) ** 2returns approximately28.27. But a negative radius has no geometric meaning. The formula silently returns a positive number, which is misleading.
Guard for negative input:
import math
radius = float(input("Enter the radius: "))
if radius < 0:
raise ValueError(f"Radius cannot be negative. Got {radius}.")
area = math.pi * radius ** 2
print(f"Area = {area:.4f}")
The guard raises a ValueError for any negative value. A radius of 0 passes through cleanly, which is the correct geometric behaviour.
Function Form and Reusability
Encapsulating the logic in a function makes the code importable and testable:
import math
def area_of_circle(radius: float) -> float:
"""Return the area of a circle with the given radius."""
if radius < 0:
raise ValueError(f"Radius cannot be negative. Got {radius}.")
return math.pi * radius ** 2
print(f"{area_of_circle(5):.4f}") # 78.5398
print(f"{area_of_circle(0):.4f}") # 0.0000
The -> float return type annotation makes the interface explicit. For placement coding tests, the function form is often the expected structure: clean, readable, and independently testable.
For practice on similar math-in-Python patterns, the Python basic programs guide covers a range of numeric operations. The calculator program in Python shows how to combine multiple formulas behind a menu interface.
Beyond the Circle: Annulus and Sector
Annulus (Ring Shape)
An annulus is the region between two concentric circles with outer radius R and inner radius r. The area is π × (R² − r²):
import math
def area_of_annulus(R: float, r: float) -> float:
if R < r:
raise ValueError("Outer radius R must be greater than or equal to inner radius r.")
return math.pi * (R ** 2 - r ** 2)
print(f"{area_of_annulus(7, 4):.2f}") # 103.67
Sector (Pie Slice)
A sector with central angle θ in radians and radius r has area ½ × r² × θ:
import math
def area_of_sector(radius: float, angle_rad: float) -> float:
return 0.5 * radius ** 2 * angle_rad
# 60 degrees = math.pi / 3 radians; radius = 5
print(f"{area_of_sector(5, math.pi / 3):.4f}") # 13.0900
For working with arrays of radii across a dataset, the sum of array elements guide covers the NumPy workflow patterns that apply to bulk area calculations too.
The choice between math.pi for a single value and numpy.pi for array operations is exactly the kind of float-precision decision that carries into data-preprocessing pipelines for AI. TinkerLLM walks through that progression from Python numeric programs to LLM input handling, starting at ₹299.
Primary sources
Frequently asked questions
What is the formula for the area of a circle in Python?
The formula is `math.pi * radius ** 2`. Import the math module and pass the radius as a float for accurate results.
What does math.pi give in Python?
math.pi returns 3.141592653589793, the IEEE 754 double-precision approximation of pi, accurate to 15 significant figures.
Should I use int() or float() for radius input in Python?
Use float(). A radius like 5.5 is geometrically valid and float(input()) handles both whole numbers and decimals cleanly.
How do I handle a negative radius in Python?
Check if radius < 0 after reading input and raise a ValueError. A negative radius has no geometric meaning and the formula would silently return a misleading positive value.
What is the difference between math.pi and numpy.pi in Python?
Both equal 3.141592653589793 (IEEE 754 double precision). Use numpy.pi when working with NumPy arrays so the constant broadcasts correctly across all array elements.
What is the area of a circle with radius 5 in Python?
Running `import math; print(math.pi * 5**2)` outputs 78.53981633974483. Formatted to 4 decimal places with f-strings: 78.5398.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)