Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Calculate the Area of a Circle in Python

Use math.pi and the radius to calculate a circle’s area, format the result, and handle invalid input in a reusable Python function.

Table of Contents

Use math.pi * radius ** 2 to calculate a circle’s area in Python. If the radius is 5 centimeters, the area is approximately 78.54 square centimeters. If you have the diameter, divide it by two to get the radius.

How to calculate the area of ​​a circle in Python Picture 1

Calculate the area with math.pi

import math

radius = 5
area = math.pi * radius ** 2
print(f"{area:.2f}")  # 78.54

The ** operator raises the radius to the power of 2. math.pi provides Python’s floating-point approximation of π. The format :.2f rounds the displayed result to two decimal places while preserving the value in area.

Use a function when you need to repeat the calculation

import math


def circle_area(radius):
    if not math.isfinite(radius) or radius < 0:
        raise ValueError("Radius must be finite and non-negative.")
    return math.pi * radius ** 2


try:
    radius = float(input("Radius: "))
    print(f"Area: {circle_area(radius):.2f} square units")
except ValueError as error:
    print(f"Invalid input: {error}")

Try 0 to check the boundary case and a negative value to check the error handling. See Python functions and scope or practice another example in the guided functions lab.

Calculate several areas at once

For a list of radii, use [circle_area(r) for r in radii]. If you already use NumPy and have an array of valid non-negative radii, use np.pi * radii ** 2 to calculate an array of areas. The standard library is enough for a single radius.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.