SOME OBJECT ORIENTED PROGRAMMING QUESTIONS IN PYHTON FOR ENGINEERING STUDENTS.
SOME OBJECT ORIENTED PROGRAMMING QUESTIONS IN PYHTON FOR ENGINEERING STUDENTS.
- Question: Create a class named
Rectanglewith two attributeswidthandheight. Create a method namedareawhich will calculate the area of the rectangle. Create a method namedperimeterwhich will calculate the perimeter of the rectangle. Create an object of theRectangleclass and print its area and perimeter.
Answer:
pythonclass Rectangle:
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)
# Creating an object of Rectangle class
rect = Rectangle(5, 10)
# Printing area and perimeter of the rectangle
print("Area:", rect.area())
print("Perimeter:", rect.perimeter())Output:
Area: 50
Perimeter: 30
- Question: Create a class named
BankAccountwith two attributesbalanceandowner_name. Create a method nameddepositwhich will add an amount to the balance. Create a method namedwithdrawwhich will subtract an amount from the balance. If the withdrawal amount is greater than the balance, print "Insufficient balance". Create an object of theBankAccountclass and perform some transactions.
Answer:
pythonclass BankAccount:
def __init__(self, owner_name, balance=0):
self.owner_name = owner_name
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance")
else:
self.balance -= amount
# Creating an object of BankAccount class
acct = BankAccount("John")
# Depositing some money
acct.deposit(1000)
# Withdrawing some money
acct.withdraw(500)
# Trying to withdraw more than the balance
acct.withdraw(10000)
# Printing the balance
print("Balance:", acct.balance)Output:
Insufficient balance
Balance: 500
- Question: Create a class named
Personwith two attributesnameandage. Create a method nameddisplaywhich will print the name and age of the person. Create a class namedStudentwhich inherits from thePersonclass and has an additional attributeroll_no. Override thedisplaymethod of thePersonclass in theStudentclass to print the name, age, and roll number of the student. Create an object of theStudentclass and call itsdisplaymethod.
Answer:
pythonclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
class Student(Person):
def __init__(self, name, age, roll_no):
super().__init__(name, age)
self.roll_no = roll_no
def display(self):
super().display()
print("Roll No:", self.roll_no)
# Creating an object of Student class
student = Student("John", 20, 1234)
# Calling the display method of Student class
student.display()Output:
Name: John
Age: 20
Roll No: 1234SOME MORE IMPORTANT QUESTIONS WILL BE UPDATED IN FEW HOURS .
STAY TUNED.

No comments