0% found this document useful (0 votes)
22 views21 pages

Python Oop Assignment Result.pdf 20250310 095423 0000

The document outlines a series of Python programming assignments focusing on various concepts such as multiple inheritance, polymorphism, abstraction, and class structures. It includes specific tasks like creating classes for employees, vehicles, triangles, and implementing game logic, as well as methods to check angles and properties of triangles. Each assignment is accompanied by code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

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

Python Oop Assignment Result.pdf 20250310 095423 0000

The document outlines a series of Python programming assignments focusing on various concepts such as multiple inheritance, polymorphism, abstraction, and class structures. It includes specific tasks like creating classes for employees, vehicles, triangles, and implementing game logic, as well as methods to check angles and properties of triangles. Each assignment is accompanied by code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

accserver81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

OOP’S ASSIGNMENT

Q1. Write a Python program to demonstrate multiple inheritance. 1. Employee class

has 3 data members EmployeeID, Gender (String), Salary


and PerformanceRating(Out of 5) of type int. It has a get() function to get these
details from the user.

2. JoiningDetail class has a data member DateOfJoining of type Date and a


function getDoJ to get the Date of joining of employees.
3. Information Class uses the marks from Employee class and the
DateOfJoining date from the JoiningDetail class to calculate the top 3
Employees based on their Ratings and then Display, using readData, all the
details on these employees in Ascending order of their Date Of Joining.

Ans . from datetime import date

class Employee:

def _init_(self, EmployeeID, Gender, Salary, PerformanceRating, DateOfJoining):

self.EmployeeID = EmployeeID self.Gender

= Gender self.Salary = Salary

self.PerformanceRating =

PerformanceRating self.DateOfJoining =

DateOfJoining

def get_details(self):

self.EmployeeID = input("Enter Employee ID:

") self.Gender = input("Enter Gender: ")


self.Salary = int(input("Enter Salary: ")) self.PerformanceRating =

int(input("Enter Performance Rating (out of 5): ")) year = int(input("Enter

Year of Joining: ")) month = int(input("Enter Month of Joining: ")) day =

int(input("Enter Day of Joining: ")) self.DateOfJoining = date(year,

month, day)

def _str_(self):

return f"ID: {self.EmployeeID}, Gender: {self.Gender}, Salary: {self.Salary}, Rating:


{self.PerformanceRating}, Joining Date: {self.DateOfJoining}"

Q.2 Write a Python program to demonstrate Polymorphism. 1. Class Vehicle with a

parameterized function Fare, that takes input value as


fare and returns it to calling Objects.

2. Create five separate variables Bus, Car, Train, Truck and Ship that call the
Fare function.
3. Use a third variable TotalFare to store the sum of fare for each Vehicle Type.
4. Print the TotalFare.

Ans. class

Vehicle:

def Fare(self, fare):

return fare

Bus = Vehicle()

Car = Vehicle()

Train = Vehicle()
Truck = Vehicle()

Ship = Vehicle()

BusFare = Bus.Fare(100)

CarFare = Car.Fare(70)

TrainFare = Train.Fare(110)

ShipFare = Ship.Fare(115)

TotalFare = BusFare + CarFare + TrainFare +

ShipFare print(TotalFare) The Output is “395”.

Q3. Consider an ongoing test cricket series. Following are the names of the
players and their scores in the test1 and 2.
Test Match 1 : Dhoni : 56 , Balaji : 94

Test Match 2 : Balaji : 80 , Dravid : 105

Calculate the highest number of runs scored by an individual cricketer in both


of the matches. Create a python function Max_Score (M) that reads a dictionary
M that recognizes the player with the highest total score. This function will
return ( Top player , Total Score ) . You can consider the Top player as String
who is the highest scorer and Top score as Integer . Input : Max_Score({‘test1’:

{‘Dhoni’:56, ‘Balaji : 85}, ‘test2’:{‘Dhoni’ 87,


‘Balaji’’:200}}) Output : (‘Balaji ‘ , 200)

Ans. def

Max_Score(M):
top_player = ""

top_score = 0

for match, scores in M.items():

for player, score in scores.items():

total_score = sum(score for match_scores in M.values()

for p, score in match_scores.items() if p == player)

if total_score > top_score:

top_score = total_score

top_player = player

return (top_player, top_score)

scores = {'test1': {'Dhoni': 56, 'Balaji': 85}, 'test2': {'Dhoni': 87, 'Balaji': 200}}

top_player, top_score = Max_Score(scores) print(f"Top Player:

{top_player}, Total Score: {top_score}")

The Output is “Top Player: Balaji, Total Score: 285”.


Q4. Create a simple Card game in which there are 8 cards which are randomly chosen
from a deck. The first card is shown face up. The game asks the player to predict
whether the next card in the selection will have a higher or lower value than the
currently showing card. For example, say the card that’s shown is a 3. The player
chooses “higher,” and the next card is shown. If that card has a higher value, the player
is correct. In this example, if the player had chosen “lower,” they would have been
incorrect. If the player guesses correctly, they get 20 points. If they choose incorrectly,
they lose 15 points. If the next card to be turned over has the same value as the previous
card, the player is incorrect.

Ans. import random

card_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,

'9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}

deck = list(card_values.keys()) * 4

random.shuffle(deck)

score = 0

current_card = deck.pop(0)

print(f"The first card is: {current_card}")

for i in range(7):

guess = input("Will the next card be higher or lower? (h/l): ").strip().lower()

if guess not in ['h', 'l']:

print("Invalid input. Please enter 'h' for higher or 'l' for lower.")

continue
next_card = deck.pop(0) print(f"The

next card is: {next_card}")

if card_values[next_card] > card_values[current_card]:

result = 'higher'

elif card_values[next_card] < card_values[current_card]:

result = 'lower'

else:

result = 'same'

if result == 'same':

print("Incorrect! The cards are the

same.") score -= 15

elif (result == 'higher' and guess == 'h') or (result == 'lower' and guess == 'l'):

print("Correct!")

score += 20

else:

print("Incorrect!")

score -= 15

current_card = next_card

print(f"Game over! Your final score is: {score}")


Q5. Create an empty dictionary called Car_0 . Then fill the dictionary with Keys : color
, speed , X_position and Y_position. car_0 = {'x_position': 10, 'y_position': 72, 'speed':
'medium'} .

a) If the speed is slow the coordinates of the X_pos get incremented by 2.

b) If the speed is Medium the coordinates of the X_pos gets incremented by 9.

c) Now if the speed is Fast the coordinates of the X_pos gets incremented by
22. Print the modified dictionary.
Ans. Car_0 = {} Car_0 = {'color': 'red', 'speed': 'medium', 'X_position': 10,

'Y_position': 72}

if Car_0['speed'] == 'slow':

Car_0['X_position'] += 2

elif Car_0['speed'] == 'Medium':

Car_0['X_position'] += 9

elif Car_0['speed'] == 'fast':

Car_0['X_position'] += 22

print(Car_0)

The Output we get: {'color': 'red', 'speed': 'medium', 'X_position': 10, 'Y_position': 72}

Q6. Show a basic implementation of abstraction in python using the abstract


classes. 1. Create an abstract class in python. 2. Implement abstraction with the
other classes and base class as abstract class.
Ans. from abc import ABC, abstractmethod
class Parent(ABC):

@abstractmethod def

relationship(self):

pass

class Son(Parent):

def relationship(self):

print("he is my son")

class Daughter(Parent):

def relationship(self):

print("she is my daughter")

#Let do this in Example form to form

output. son = Son() daughter = Daughter()

son.relationship()

daughter.relationship()

The output you see:

he is my son

She is my daughter
Q7. Create a program in python to demonstrate Polymorphism. 1. Make use of private
and protected members using python name mangling techniques.
Ans.
class Car:

def _init_(self):

self.__engine = 'V12'

self._Name = 'Konisegg Egera'

self.__topspeed = "489kmph"

def _protected_method(self):

print("you have to enter the write code")

def display_info(self):

print(f"Engine: {self.__engine}")

print(f"Name: {self._Name}")

print(f"topspeed : {self.__topspeed}")

obj = Car()

obj.display_info()

#USING MANGLING TECHINQUE:

print(f" {obj.Car_engine}")

print(f"{obj.Car_topspeed}")

The Output is:

Engine: V12 Name:

Konisegg Egera

topspeed : 489kmph
The Mangling Outputs: V12 489kmph.
Q8. Given a list of 50 natural numbers from 1-50. Create a function that will take every
element from the list and return the square of each element. Use the python map and
filter methods to implement the function on the given list.
Ans. def square_elements(data):

filtered_data = filter(lambda x: True, data)

squared_data = map(lambda x: x**2, filtered_data)

return list(squared_data)

numbers = list(range(1, 51))

squared_numbers = square_elements(numbers)

print(squared_numbers)

The Output is:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576,
625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764,
1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]
Q9. Create a class, Triangle. Its init() method should take self, angle1, angle2, and
angle3 as arguments.
Ans class triangle: def _init_(self,

angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3
Lets Take an example: triangle1 = triangle(60,60,60) triangle2 =

triangle(30,60,90) triangle3 = triangle(45,45,90) print("triangle1 angles:",

triangle1.angle1 ,triangle1.angle2, triangle1.angle3) The output is: triangle1

angles: 60 60 60

Q10. Create a class variable named number_of_sides and set it equal to 3.


Ans. class

triangle:

number_of_sides = 3 def _init_(self, angle1

, angle2 , angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

print(triangle.number_of_sides)

my_triangle = triangle(60,60,60)

The output we get :

Q11. Create a method named check_angles. The sum of a triangle's three angles should
return True if the sum is equal to 180, and False otherwise. The method should print
whether the angles belong to a triangle or not.
Ans.
class Triangle:

number_of_sides = 3

def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 == 180:

print("the angles are belong to

Triangle") return True

else:

print("The angles are not belong to

Triangle") return False

my_triangle = Triangle(60,60,60) result = my_triangle.check_angles() print(result) The Output

we get: the angles are belong to Triangle True


11.1 Write methods to verify if the triangle is an acute triangle or obtuse triangle.

Ans. class

Triangle:

number_of_sides = 3
def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 <= 180:

print("The Triangle is an acute

Triangle") return True

else:

print("The Triangle is an obtuse

Triangle") return False

my_triangle = Triangle(120,60,45)

result = my_triangle.check_angles()

print(result)

my_triangle = Triangle(30,60,45)

result = my_triangle.check_angles()

print(result)

The Output we get: The

Triangle is an obtuse Triangle

False
The Triangle is an acute Triangle True.
11.2 Create an instance of the triangle class and call all the defined methods.
Ans. class Triangle:

number_of_sides = 3

def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 == 180:

print("the angles are belong to

Triangle") return True

elif self.angle1 + self.angle2 + self.angle3 <= 180:

print("The Triangle is an acute

angle") return False

else:

print("The Triangle is an obtuse

angle") return False

Lets Take an Example:


my_triangle = Triangle(60,30,45)

result = my_triangle.check_angles()
print(result)

The Output We get:

The Triangle is an acute angle

False.

11.3 Create three child classes of triangle class - isosceles_triangle,


right_triangle and equilateral_triangle.
Ans. class Triangle:

number_of_sides = 3

def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 == 180:

return True

else:

return False

class isosceles_triangle(Triangle):

def _init_(self, angle1 , angle2):

super()._init_(angle1,angle2,angle2)

print("This is an isosceles Triangle")


class right_triangle(Triangle):

def _init_(self, angle1,angle2):

super()._init_(angle1, angle2 , 90)

print("This is an right Triangle")

class equilateral_triangle(Triangle):

def _init_( self):

super()._init_(60,60,60) print("This is

an Equilateral Triangle")

iso_triangle = isosceles_triangle(40, 70)

print(iso_triangle.check_angles())

right_triangle = right_triangle(30, 60)

print(right_triangle.check_angles())

equilateral_triangle = equilateral_triangle()

print(equilateral_triangle.check_angles())

The Output We get: This

is an isosceles Triangle

True
This is an right

Triangle True

This is an Equilateral Triangle

True.

11.4 DEFINE METHODS WHICH CHECK


FOR THEIR PROPERTIES.
Ans. class Triangle:

number_of_sides = 3

def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 == 180:

return True

else:

return False

class isosceles_triangle(Triangle):

def _init_(self, angle1, angle2):

super()._init_(angle1, angle2, angle2)

print("This is isosceles Triangle")


def is_isosceles(self):

"""Checks if the triangle is isosceles (two angles equal).""" return self.angle1 ==

self.angle2 or self.angle2 == self.angle3 or self.angle1 == self.angle3

class right_triangle(Triangle):

def _init_(self, angle1, angle2):

super()._init_(angle1, angle2, 90)

print("This is right Triangle")

def is_right(self):

"""Checks if the triangle is a right triangle (one angle is 90 degrees)."""

return self.angle1 == 90 or self.angle2 == 90 or self.angle3 == 90

class equilateral_triangle(Triangle):

def _init_(self):

super()._init_(60, 60, 60) print("This

is Equilateral Triangle")

def is_equilateral(self):

"""Checks if the triangle is equilateral (all angles are 60 degrees)."""

return self.angle1 == 60 and self.angle2 == 60 and self.angle3 == 60

iso_triangle = isosceles_triangle(40, 70)

print(iso_triangle.check_angles())
right_triangle = right_triangle(30, 60)

print(right_triangle.check_angles())

equilateral_triangle = equilateral_triangle()

print(equilateral_triangle.check_angles())

The Output we get:

This is isosceles Triangle

True

This is right Triangle

True

This is Equilateral Triangle

True
Q12. Create a class isosceles_right_triangle which inherits from
isosceles_triangle and right_triangle.
Ans. class

Triangle:

number_of_sides = 3

def _init_(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3
def check_angles(self):

if self.angle1 + self.angle2 + self.angle3 == 180:

return True

else:

return False

class isosceles_triangle(Triangle):

def _init_(self, angle1, angle2):

super()._init_(angle1, angle2)

def is_isosceles(self):

return self.angle1 == self.angle2 or self.angle2 == self.angle3 or self.angle1 == self.angle3

class right_triangle(Triangle):

def _init_(self, angle1, angle2):

super()._init_(angle1, angle2, 90)

def is_right(self):

return self.angle1 == 90 or self.angle2 == 90 or self.angle3 == 90

class isosceles_right_triangle(isosceles_triangle, right_triangle):

def _init_(self, angle):

super()._init_(angle, 45) # Assume one angle is 'angle' and the other is 45

Lets Take an Example:


iso_triangle = isosceles_right_triangle(45)

result = iso_triangle.check_angles()

print(result)

iso_triangle = isosceles_right_triangle(45)

result = iso_triangle.check_angles()

print(result)

We get the output: True True.

12.1 DEFINE METHODS WHICH CHECK


FOR THEIR PROPERTIES.
Ans. class isosceles_right_triangle(isosceles_triangle, right_triangle):

def _init_(self, angle):

super()._init_(angle, 45)

def is_isosceles_right(self):

"""Checks if the triangle is both isosceles and right."""

return self.is_isosceles() and self.is_right()

You might also like