Python OOP Exercise Questions
This collection of Python OOPs coding practice problems covers everything from defining classes and objects to solving advanced challenges like implementing design patterns and creating custom data structures. Perfect for beginners and seasoned programmers looking to deepen their understanding of OOP in Python!
Example Programs
Exercise 1: Create a class Greeter with a method greet(name) that prints a greeting for the provided name.
class Greeter:
def greet(self, name):
print(f"Hello, {name}!")
# Example usage:
g = Greeter()
g.greet("Gabriel")
Output
Hello, Gabriel!
Exercise 2: Develop a class Calculator with methods to add and subtract two numbers.
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))
Output
Sum: 8 Difference: 2
Exercise 3: Build a class Employee with multiple constructors that can initialize an employee object in different ways.
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()
Output
Name: 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.
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))
Output
Sum of series: 25
Exercise 5: Create a class MaxFinder that identifies the largest number in a list.
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())
Output
The largest number is: 5
Practice Problems
- Design a class
- Constructor
- Encapsulation
- Abstraction
- Static Method
- Inheritance
- Multiple inheritence
- Method Overriding
- Operator Overloading