Python OOPs Exercise Questions
Last Updated :
21 Jan, 2025
Ready to level up your Python object-oriented programming skills? Explore our collection of Python OOP exercises, packed with over 25 engaging problems to help you master core concepts like encapsulation, inheritance, polymorphism and abstraction. Let’s turn theory into practice!
Python OOPs Practice Programs
This Python OOP exercise is crafted to strengthen your understanding of Python Object-Oriented Programming (OOP) concepts and sharpen your coding skills. These programs provide practical experience in solving real-world problems using OOP principles, reinforcing essential concepts like encapsulation, inheritance, polymorphism, and abstraction. Whether you're a beginner building a strong foundation in OOP or a seasoned developer looking to refine your expertise, our practice exercises offer an excellent opportunity to enhance your skills and excel in object-oriented design and programming with Python.
Exercise 1: Create a class Greeter with a method greet(name) that prints a greeting for the provided name.
Solution:
Python
class Greeter:
def greet(self, name):
print(f"Hello, {name}!")
# Example usage:
g = Greeter()
g.greet("Anurag")
Exercise 2: Develop a class Calculator
with methods to add and subtract two numbers.
Python
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
# Testing the calculator
calc = Calculator()
print("Sum:", calc.add(5, 3))
print("Difference:", calc.subtract(5, 3))
OutputSum: 8
Difference: 2
Exercise 3: Build a class Employee with multiple constructors that can initialize an employee object in different ways.
Python
class Employee:
def __init__(self, name, id=None, department=None):
self.name = name
self.id = id
self.department = department
def display_details(self):
print(f"Name: {self.name}")
if self.id:
print(f"ID: {self.id}")
if self.department:
print(f"Department: {self.department}")
# Examples
emp1 = Employee("John")
emp1.display_details()
emp2 = Employee("Doe", 101)
emp2.display_details()
emp3 = Employee("Jane", 102, "HR")
emp3.display_details()
OutputName: John
Name: Doe
ID: 101
Name: Jane
ID: 102
Department: HR
Exercise 4: Design a class SeriesCalculator that calculates the sum of an arithmetic series.
Python
class SeriesCalculator:
def calculate_sum(self, n, a=1, d=2):
# Sum of the first n terms of an arithmetic series
return n * (2 * a + (n - 1) * d) // 2
# Test the calculator
sc = SeriesCalculator()
print("Sum of series:", sc.calculate_sum(5))
Exercise 5: Create a class MaxFinder that identifies the largest number in a list.
Python
class MaxFinder:
def __init__(self, numbers):
self.numbers = numbers
def find_max(self):
if not self.numbers:
return "List is empty"
return max(self.numbers)
# Example
finder = MaxFinder([1, 3, 2, 5, 4])
print("The largest number is:", finder.find_max())
OutputThe largest number is: 5
Exercise 6: Design a Rectangle class with default attributes for length and width set to 1. Include methods to set these attributes and calculate the area.
Python
class Rectangle:
def __init__(self, length=1, width=1):
self.length = length
self.width = width
def set_dimensions(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Example usage:
rect = Rectangle()
print("Default area:", rect.area())
rect.set_dimensions(4, 5)
print("Updated area:", rect.area())
OutputDefault area: 1
Updated area: 20
Exercise 7: Person Class with __str__ Method: Create a Person class with first and last name attributes and override the __str__ method to return the full name.
Python
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __str__(self):
return f"{self.first_name} {self.last_name}"
# Example usage:
person = Person("John", "Doe")
print(person)
Exercise 8: Student Grade Calculator: Implement a Student class with attributes for name and a list of marks. Include a method to calculate the average and determine the grade.
Python
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def average(self):
return sum(self.marks) / len(self.marks)
def grade(self):
average = self.average()
if average >= 90:
return 'A'
elif average >= 80:
return 'B'
elif average >= 70:
return 'C'
elif average >= 60:
return 'D'
else:
return 'F'
# Example usage:
student = Student("Alice", [92, 88, 91])
print(f"{student.name} Grade: {student.grade()}")
Exercise 10: Last Digit in Words: Write a class with a method that takes an integer and prints the last digit of that number in words.
Python
class NumberInWords:
def last_digit_in_words(self, number):
last_digit = number % 10
words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
return words[last_digit]
# Example usage:
niw = NumberInWords()
print(niw.last_digit_in_words(123))
Exercise 11: Object Count Tracker: Design a class that tracks how many objects have been created from it and has a method to display this count.
Python
class ObjectCounter:
count = 0
def __init__(self):
ObjectCounter.count += 1
@staticmethod
def display_count():
print("Number of objects created:", ObjectCounter.count)
# Example usage:
a = ObjectCounter()
b = ObjectCounter()
ObjectCounter.display_count()
OutputNumber of objects created: 2
Exercise 12: Calculating Student Results: Develop a class to accept a student's name and marks in three subjects, then calculate and display the total and average marks.
Python
class StudentResult:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def total(self):
return sum(self.marks)
def average(self):
return self.total() / len(self.marks)
def display(self):
print(f"Student: {self.name}")
print(f"Total Marks: {self.total()}")
print(f"Average Marks: {self.average()}")
# Example usage:
sr = StudentResult("Bob", [76, 84, 90])
sr.display()
OutputStudent: Bob
Total Marks: 250
Average Marks: 83.33333333333333
Exercise 13: Car Class: Create a Car class with attributes make, model, and year. Include a method to display the details of the car.
Python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_details(self):
print(f"Make: {self.make}, Model: {self.model}, Year: {self.year}")
# Example usage:
my_car = Car("Toyota", "Corolla", 2021)
my_car.display_details()
OutputMake: Toyota, Model: Corolla, Year: 2021
Exercise 14: Inheritance - Animal Kingdom: Create a base class Animal with a method speak(). Derive two classes Dog and Cat from Animal and override the speak method to reflect their sounds.
Python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
# Example usage:
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
Exercise 15: Polymorphism with a Function: Create a function describe_pet that takes an object of Animal and calls its speak method, demonstrating polymorphism.
Python
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
class Parrot(Animal):
def speak(self):
print("Squawk!")
def describe_pet(animal):
animal.speak()
# Example usage:
dog = Dog()
cat = Cat()
parrot = Parrot()
describe_pet(dog)
describe_pet(cat)
describe_pet(parrot)
OutputWoof!
Meow!
Squawk!
Exercise 16: Encapsulation - Protecting Attributes: Implement a class Account with a private attribute balance and provide methods to deposit and withdraw safely, checking for sufficient funds.
Python
class Account:
def __init__(self, balance=0):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
print(f"Deposited: {amount}, New Balance: {self.__balance}")
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient funds")
else:
self.__balance -= amount
print(f"Withdrew: {amount}, Remaining Balance: {self.__balance}")
# Example usage:
acc = Account(100)
acc.deposit(50)
acc.withdraw(100)
acc.withdraw(100)
OutputDeposited: 50, New Balance: 150
Withdrew: 100, Remaining Balance: 50
Insufficient funds
Exercise 17: Abstract Classes - Polygon Calculator: Define an abstract base class Polygon with an abstract method area. Implement this in derived classes Rectangle and Triangle.
Python
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Polygon):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Polygon):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# Example usage:
rect = Rectangle(10, 20)
tri = Triangle(10, 10)
print("Rectangle Area:", rect.area())
print("Triangle Area:", tri.area())
OutputRectangle Area: 200
Triangle Area: 50.0
Exercise 18: Multiple Inheritance - Battery and GPS Tracker: Create classes Battery and GPS with respective methods charge and location. Derive a SmartPhone class that inherits both functionalities.
Python
class Battery:
def charge(self):
print("Charging the battery")
class GPS:
def location(self):
print("Current location is 123, 456")
class SmartPhone(Battery, GPS):
pass
# Example usage:
phone = SmartPhone()
phone.charge()
phone.location()
OutputCharging the battery
Current location is 123, 456
Exercise 19: Using Property Decorators: Implement a class Circle with a private attribute radius and use property decorators to get and set its value with checks.
Python
class Circle:
def __init__(self, radius):
self.__radius = radius
@property
def radius(self):
return self.__radius
@radius.setter
def radius(self, value):
if value >= 0:
self.__radius = value
else:
print("Radius cannot be negative")
def area(self):
return 3.14159 * self.__radius ** 2
# Example usage:
circle = Circle(5)
print("Area:", circle.area())
circle.radius = -10
print("Radius:", circle.radius)
OutputArea: 78.53975
Radius cannot be negative
Radius: 5
Exercise 20: Dynamic Attribute Addition Demonstrate dynamic attribute addition where a class Vehicle starts without defined attributes and properties are added later.
Python
class Vehicle:
pass
# Example usage:
car = Vehicle()
car.make = "Toyota"
car.model = "Camry"
print(f"Car: {car.make} {car.model}")
Exercise 21: Interface Implementation Create an interface Shape with methods area() and perimeter(). Implement this interface in Rectangle and Circle classes.
Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
# Example usage:
rectangle = Rectangle(10, 20)
circle = Circle(5)
print("Rectangle Area:", rectangle.area())
print("Rectangle Perimeter:", rectangle.perimeter())
print("Circle Area:", circle.area())
print("Circle Perimeter:", circle.perimeter())
OutputRectangle Area: 200
Rectangle Perimeter: 60
Circle Area: 78.53975
Circle Perimeter: 31.4159
Exercise 22: Composition Over Inheritance: Create a Book class with a Author class included within it, demonstrating composition over inheritance.
Python
class Author:
def __init__(self, name):
self.name = name
class Book:
def __init__(self, title, author):
self.title = title
self.author = Author(author)
def display(self):
print(f"Book: {self.title}, Author: {self.author.name}")
# Example usage:
book = Book("Python Programming", "John Doe")
book.display()
OutputBook: Python Programming, Author: John Doe
Exercise 23: Operator Overloading Create a Vector class that supports addition using the + operator, allowing you to add two vectors.
Python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
# Example usage:
v1 = Vector(2, 4)
v2 = Vector(1, -1)
print("Vector Addition:", v1 + v2)
OutputVector Addition: (3, 3)
Exercise 24: Static and Class Methods Demonstrate the use of static and class methods in a class Calculator with methods to add and multiply numbers.
Python
class Calculator:
@staticmethod
def add(a, b):
return a + b
@classmethod
def multiply(cls, a, b):
return a * b
# Example usage:
print("Addition:", Calculator.add(5, 3))
print("Multiplication:", Calculator.multiply(4, 5))
OutputAddition: 8
Multiplication: 20
Exercise 25: Managing Private Attributes Create a Person class with private attributes name and age and provide getter and setter methods to manage these attributes safely.
Python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if isinstance(value, str) and len(value) > 0:
self.__name = value
else:
print("Invalid name")
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if isinstance(value, int) and value >= 0:
self.__age = value
else:
print("Invalid age")
# Example usage:
person = Person("John Doe", 30)
print("Name:", person.name)
print("Age:", person.age)
person.name = ""
person.age = -5
OutputName: John Doe
Age: 30
Invalid name
Invalid age
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read