0% found this document useful (0 votes)
16 views8 pages

Python Lab Assignment Solutions

The document contains a Python lab assignment with various programming questions focused on object-oriented concepts. Each question includes class definitions and method implementations, demonstrating inheritance, method overriding, and object instantiation. The output for each question is provided, showcasing the results of the executed code.

Uploaded by

gundalauttham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Python Lab Assignment Solutions

The document contains a Python lab assignment with various programming questions focused on object-oriented concepts. Each question includes class definitions and method implementations, demonstrating inheritance, method overriding, and object instantiation. The output for each question is provided, showcasing the results of the executed code.

Uploaded by

gundalauttham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON LAB

ASSIGNMENT [11/04/2025]
HT NO:2405A41216
BATCH :09 OUTPUT

#QUESTION : 1

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

person1 = Person("Alice", 30)


person2 = Person("Bob", 25)

print(f"Person 1: Name - {[Link]}, Age - {[Link]}")


print(f"Person 2: Name - {[Link]}, Age - {[Link]}")

OUTPUT
Person 1: Name - Alice, Age - 30

Person 2: Name - Bob, Age – 25

#QUESTION : 2

class Car:
def start(self):
print("Car starting with engine...")

class ElectricCar(Car):
def start(self):
print("Electric car starting with battery...")

car = Car()
electric_car = ElectricCar()

[Link]()
electric_car.start()

OUTPUT
Car starting with engine...

Electric car starting with battery...

#QUESTION : 3

class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks

def check_pass_fail(self):
if [Link] >= 35:
return "Passed"
else:
return "Failed"

student1 = Student("SHIVA", 40)


student2 = Student("David", 30)

print(f"{[Link]}: {student1.check_pass_fail()}")
print(f"{[Link]}: {student2.check_pass_fail()}")

OUTPUT
SHIVA: Passed

David: Failed
#QUESTION : 4

class Animal:
def sound(self):
print("Generic animal sound")

class Dog(Animal):
def sound(self):
print("Bark")

class Cat(Animal):
def sound(self):
print("Meow")

dog = Dog()
cat = Cat()

[Link]()
[Link]()

OUTPUT
Bark
Meow

#QUESTION : 5

class Calculator:
def add(self, a, b):
return a + b

def subtract(self, a, b):


return a - b

def multiply(self, a, b):


return a * b

def divide(self, a, b):


if b != 0:
return a / b
else:
return "Division by zero error"
calculator = Calculator()

print([Link](5, 3))
print([Link](10, 4))
print([Link](2, 6))
print([Link](12, 3))

OUTPUT
8
6
12
4.0

#QUESTION : 6

class Employee:
def __init__(self, name, id, salary):
[Link] = name
[Link] = id
[Link] = salary

class Manager(Employee):
def __init__(self, name, id, salary, department):
super().__init__(name, id, salary)
[Link] = department

employee = Employee("shiva", 101, 50000)


manager = Manager("vashi", 102, 80000, "HR")

print([Link], [Link], [Link])


print([Link], [Link], [Link], [Link])

OUTPUT
shiva 101 50000

vashi 102 80000 HR


#QUESTION : 7

class MyClass:
def greet(self, name="shiva"):
print("Hello,", name)

obj = MyClass()
[Link]()
[Link]("ravi")

OUTPUT
Hello, shiva

Hello, ravi

#QUESTION : 8

import math

class Shape:
def area(self):
pass

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * [Link]**2

class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width

def area(self):
return [Link] * [Link]

circle = Circle(5)
rectangle = Rectangle(4, 6)

print([Link]())
print([Link]())

OUTPUT
78.53981633974483
24

#QUESTION : 9

class Book:
total_books = 0

def __init__(self, title, author):


[Link] = title
[Link] = author
Book.total_books += 1

book1 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams")


book2 = Book("To Kill a Mockingbird", "Harper Lee")
book3 = Book("Pride and Prejudice", "Jane Austen")

print(Book.total_books)

OUTPUT
3

#QUESTION : 10

class BankAccount:
def __init__(self, account_holder, balance=0):
self._account_holder = account_holder
self._balance = balance

def deposit(self, amount):


if amount > 0:
self._balance += amount
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount

def get_balance(self):
return self._balance

account = BankAccount("shiva", 1000)


[Link](500)
[Link](200)
print(account.get_balance())

OUTPUT
1300

#QUESTION : 11

class LivingBeing:
def breathe(self):
print("Breathing...")

class Animal(LivingBeing):
def move(self):
print("Moving...")

class Dog(Animal):
def bark(self):
print("Barking...")

dog = Dog()
[Link]()
[Link]()
[Link]()

OUTPUT
Breathing...
Moving...
Barking...

Common questions

Powered by AI

The 'total_books' attribute in the 'Book' class acts as a class variable that keeps track of the number of book instances created. With each instantiation of a 'Book' object, 'total_books' is incremented, reflecting shared data across all instances. This implementation exemplifies a class-level attribute's role in managing shared state and providing a mechanism to track collective information about all objects of the class, rather than individual instances .

Inheritance is used in the 'Employee' and 'Manager' classes to establish a hierarchical relationship where 'Manager' is a subclass of 'Employee'. The 'Manager' class inherits properties like 'name', 'id', and 'salary' from 'Employee', and additionally introduces the 'department' attribute. This implementation facilitates code reuse, allowing managers to share common employee traits while expanding functionality with department-specific attributes .

The 'BankAccount' class uses encapsulation by hiding its attributes '_account_holder' and '_balance' with a leading underscore. This convention suggests that these attributes shouldn't be accessed directly from outside the class. Methods like 'deposit', 'withdraw', and 'get_balance' provide controlled access to these attributes, allowing operations to be performed while maintaining internal data security and integrity. This encapsulation helps prevent unintended modifications that could compromise account balances .

The class 'Shape' supports polymorphic behavior via its abstract 'area' method, which is meant to be implemented by subclasses like 'Circle' and 'Rectangle'. Each subclass provides a concrete implementation of 'area', computing the area specific to its geometric formula — 'Circle' uses πr², and 'Rectangle' uses length × width. This allows instances of 'Circle' and 'Rectangle' to be used interchangeably wherever a 'Shape' type is expected, with each providing its specific area computation .

The 'Student' class implements conditional logic through the 'check_pass_fail' method. This method evaluates whether a student's marks are greater than or equal to 35 by using an 'if' statement. If true, the method returns 'Passed'; otherwise, it returns 'Failed'. This conditional check allows the 'Student' class to determine and convey the pass or fail status of a student based on their marks, illustrating the application of simple conditional statements to make logical decisions .

The inheritance structure among 'LivingBeing', 'Animal', and 'Dog' is a simple multi-level hierarchy. 'Animal' inherits from 'LivingBeing', and 'Dog' inherits from 'Animal'. This setup allows a 'Dog' object to access methods defined in both 'Animal' and 'LivingBeing', such as 'breathe'. The 'Dog' class also introduces a specific 'bark' method unique to its subclass. This hierarchy facilitates method sharing across levels and encourages code reuse, enabling specific behaviors like 'bark' while maintaining basic functionalities from parent classes .

The '__init__' method in Python classes serves as a constructor to initialize an object's state upon creation. In the 'Person' class, '__init__' takes parameters 'name' and 'age' to assign the initial values to the corresponding object attributes 'self.name' and 'self.age'. This method is crucial for setting up initial conditions and ensuring objects have the necessary attributes to perform functions immediately after being instantiated .

The classes 'Car' and 'ElectricCar' demonstrate method overriding through their 'start' methods. In the base class 'Car', the 'start' method outputs 'Car starting with engine...'. The 'ElectricCar' class, which inherits from 'Car', overrides this method to output 'Electric car starting with battery...'. This shows how a subclass can provide a specific implementation for a method that is already defined in its superclass .

The 'Calculator' class implements basic error handling in its 'divide' method to prevent division by zero, which is a common source of runtime errors. By checking if the divisor 'b' is not zero before performing the division, the method avoids generating an exception and returns a meaningful message 'Division by zero error' instead. This preventative measure ensures that the program handles potential errors gracefully, maintaining stability and providing users with prompt feedback on invalid operations .

Polymorphism in the 'Animal', 'Dog', and 'Cat' classes is demonstrated through the 'sound' method. The base class 'Animal' defines a generic 'sound' method. Both 'Dog' and 'Cat' subclasses override this method to provide specific implementations ('Bark' for dogs and 'Meow' for cats). This allows objects of these subclasses to be treated as instances of their parent class, enabling them to exhibit behavior specific to their subclass automatically .

You might also like