← Previous Module 8: Classes & Objects Next →
Statement
Solution

Python Exercise 8.1: The Circle Class

Object-Oriented Programming (OOP) lets you bundle data and behaviour together in a class. Write a Circle class that stores a radius and can calculate its area and circumference.

Your class should:

  • Define a class called Circle.
  • Include an __init__ method that accepts a radius parameter and stores it as an instance attribute.
  • Include an area() method that returns π × radius². Use math.pi for π.
  • Include a circumference() method that returns 2 × π × radius.
  • Create an instance of Circle with a radius of 7 and print both values rounded to 2 decimal places.

Sample Interaction:

Input
Output
(None)
Area: 153.94 Circumference: 43.98

Solution

We define the class with an __init__ constructor and two methods, then create an object and call each method.

import math class Circle: def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 def circumference(self): return 2 * math.pi * self.radius # Create an instance with radius 7 c = Circle(7) print(f"Area: {c.area():.2f}") print(f"Circumference: {c.circumference():.2f}")

Key Concepts:

  • class ClassName: defines a new class.
  • __init__ is the constructor — it runs automatically when an object is created.
  • self refers to the current instance of the class.
  • Instance attributes (e.g. self.radius) store data specific to each object.
  • :.2f inside an f-string rounds a float to 2 decimal places.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top