Python program to calculate circle area

Introduction

Welcome to a new code snippet in Python. This post is a beginner level one in which we are going to implement a basic Python class to represent a circle and be able to compute the area using different methods. You will learn how to define a class in Python, use default parameter values and utilize the math module. Let us do that...

Circle area

Circle area can be calculated in difference ways…


Area = PI * R * R where R is the radius
Area = (PI * D * D)/4 where D is the diameter
Area = (C * C/4 * PI) where C is the circumference

Let us implement these formulas in Python...

Circle area in Python

# Import math module so that we can use pi
import math

# Define a circle class
class Circle:
    # Constructor: initialize with 
    # radius or diameter or circumference
    # For example, if you do not want to
    # use the radius, just leave it 0
    # Note that we used default values of 0
    # It is a trick to know how the user
    # wants to calculate the area
    def __init__(self, r=0, d=0, c=0):   
        # Radius
        self.r = r
        # Diameter
        self.d = d 
        # Circumference
        self.c = c

    # Calculate area
    def area(self):
        # Using radius
        if self.r > 0:
            # ** is used to raise a number to a power
            return math.pi * self.r ** 2
        # Using diameter
        if self.d > 0:
            return (math.pi * self.d ** 2)/4
        # Using circumference
        if self.c > 0:
            return (self.c ** 2)/(4 * math.pi)

# Create a circle object to test our code

# Using radius, note that we did not provide
# values for diameter and circumference so
# the default values are going to be 0 therefore
# they are not going to be used in the calculation
circle = Circle(10)
print(circle.area())

# Using diameter, note that the first parameter
# has to be provided even though we do not want
# to use it in the calculation
circle = Circle(0, 10)
print(circle.area())

# Using circumference, note that the first and second
# parameters need to be provided even though they are
# not used in the calculation
circle = Circle(0, 0, 10)
print(circle.area())

If you run the code snippet above, you should get the following output...

314.159265359
78.5398163397
7.95774715459

Summary

  • Circle area can be calculated in different ways depending on what we know in advance such as the radius, diameter or circumference
  • Class keyword in Python is used to define a class of objects. To provide a constructor, use __init__ method
  • We can provide default values to method parameters in method signature
  • Math module is a good choice for all sorts of mathematical computation. In this post, we used math.pi

Thanks for reading. Please use the comments section below for feedback.

Search Terms...
Tags:

Leave a Reply