0% found this document useful (0 votes)
33 views27 pages

Practical File Final

The document contains a lab report submitted by a student for an Object Oriented Programming lab. It includes 12 programs covering OOP concepts like class and object creation, inheritance, polymorphism, abstraction, and more. For each program, tasks to be completed are provided along with the Python code implementing the tasks.

Uploaded by

akshatraj875
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)
33 views27 pages

Practical File Final

The document contains a lab report submitted by a student for an Object Oriented Programming lab. It includes 12 programs covering OOP concepts like class and object creation, inheritance, polymorphism, abstraction, and more. For each program, tasks to be completed are provided along with the Python code implementing the tasks.

Uploaded by

akshatraj875
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/ 27

Plot No.

2, Sector 17-A, Yamuna Expressway,


Greater Noida, Gautam Buddh Nagar, U.P., India

School of Computer
Science And
Engineering

Lab Report
B. Tech- II Sem
Winter: 2023-24

Submitted by: Submitted to:


Name:......................... ……………………..
Batch:....……………..
Adm No:.…………….
Object Oriented Programming Lab Programs

Ex.No. Program Title


Creating a Class and Object:
(i). Create a Python class called “Car” with attributes like
make, model, and year. Then, create an object of the “Car”
class and print its details.
(ii). Write Python program to simulate a car dealership's
inventory management system. The system aims to model
cars and their attributes accurately.
Task-1. You are tasked with creating a Python program to
1. represent vehicles using a class. Each car should have
attributes for maximum speed and mileage.
Task-2. Update the class with the default color for all
vehicles," white".
Task-3. Additionally, you need to create methods in the
Vehicle class to assign seating capacity to a vehicle.
Task-4. Create a method to display all the properties of an
object of the class.
Task-5. Additionally, you need to create two objects of the
Vehicle class object that should have a max speed of 200kph
and mileage of 50000kmpl with five seating capacities, and
another car object should have a max speed of 180kph and
75000kmpl with four seating capacities.
Class with constructor:
Write a program find Euclidean distance between two pints
2. in a three-dimensional space using class and objects. Class
called point consists of a constructor ( init ()) and two
functions # distancefromorgin() and distance().
Inheritance:
(i). Create a base class called “Animal” and two subclasses,
“Dog” and “Cat.” Add methods and attributes specific to
each subclass.
(ii). Create a Bus child class that inherits from the Vehicle
class. The default fare charge of any vehicle is seating
3. capacity * 100. If Vehicle is Bus instance, we need to add an
extra 10% on full fare as a maintenance charge. So total fare
for bus instance will become the final amount = total fare +
10% of the total fare.

Note: The bus seating capacity is 50. so the final fare


amount should be 5500. You need to override the fare()
method of a Vehicle class in Bus class.

Polymorphism:
Create a function that takes an animal object as input and
4. calls its “sound” method. Test it with both a dog and a cat
object and utilize base class called “Animal” and two
subclasses, “Dog” and “Cat.” Add methods and attributes
specific to each subclass.
Multiple Inheritance:
Create three classes, “Person,” “Employee,” and “Student.”
5. Use multiple inheritance to create a class “PersonInfo” that
inherits from both “Employee” and “Student.” Add
attributes and methods specific to each class.
Abstract Base Classes:
Create an abstract base class called “Shape” with an abstract
6. method called “area.” Implement two subclasses, “Circle”
and “Rectangle,” that inherit from “Shape” and provide their
own implementations of the “area” method.
Class Methods and Static Methods:
Create a class called “MathUtils” with class methods for
7. calculating the factorial of a number and a static method to
check if a number is even.
Composition:
8. Write python code create classes for “Author” and “Book.”
The “Book” class should have an “Author” object as an
attribute, demonstrating composition.
Operator Overloading:
9. Write python code to concatenate the two given strings
using Operator Overloading.

Exception Handling:
Write python code to create a class called “Calculator” with
10. methods for addition, subtraction, multiplication, and
division. Handle exceptions like division by zero gracefully
and raise custom exceptions when needed.
Composition with Aggregation:
Write python code to create classes for “Department” and
11. “Employee.” Use aggregation to represent that an Employee
belongs to a Department. Implement methods to add
employees to a department and calculate the average salary
of employees in a department.
Method Overriding:
Create a base class called “Vehicle” with a method called
12. “drive.” Implement two subclasses, “Car” and “Bicycle,” that
inherit from “Vehicle” and override the “drive” method with
their own implementations.
Lamda functions:
Write python code to perform the following Lamda function
below:
(i) Map()
13. (ii) filter()
(iii) lambda function to calculate grades for a list of scores.
(iv) List Comprehensions.
(v) calculates the factorial of a number using a recursive
lambda function
Loan Calculator using Tkinter:
(i). Write python GUI application is developed for computing
loan payments. The code consists of the following steps:
1. Design the user interface consisting of labels using Label( ),
text entry boxes using Entry( ), and a button using Button( ).
14. 2. Process the event. When the button is clicked, the
program invokes a callback functions, using
getMonthlyPayment( ) to obtain the user input for the
interest rate, number of years, and loan amount from the
text entries. The monthly and total payments are computed
using computePayment( ) and displayed in the labels.
Popup Menu based Arithmetic Operations using Tkinter:
Creating a popup menu is similar to creating a regular menu.
First, you create an instance of Popup menu using Menu( ),
and then you can add items to it using
menu.add_command( ). Finally, you bind a widget with an
event to pop up the menu. Popup menu commands are
used to perform actions to be displayed in a canvas which is
created using canvas( ).
The canvas widget is used to add the structured graphics to
15. the python application. It is used to display text, images,
graph and plots to the python application. The menu items
use callback functions to instruct the canvas to perform
actions.
In code, a popup menu is displayed by clicking the right
mouse button followed by binding it with the canvas using
canvas.bind( ). Each item in the popup menu is selected to
perform the corresponding arithmetic operations. The
inputs are obtained in two textboxes and the output is
displayed in one textbox.
Display an Image and its Transformation using Tkinter and
16. OpenCV-Python:
(i).Program to read and display an RGB color image and
convert it into grayscale, negative and edge images.
Practical File
1. Creating a Class and Object:

(i). Create a Python class called “Car” with attributes like make, model, and year. Then,
create an object of the “Car” class and print its details.

(ii). Write Python program to simulate a car dealership's inventory management system.
The system aims to model cars and their attributes accurately.

Task-1. You are tasked with creating a Python program to represent vehicles using a class.
Each car should have attributes for maximum speed and mileage.

Task-2. Update the class with the default color for all vehicles," white".

Task-3. Additionally, you need to create methods in the Vehicle class to assign seating
capacity to a vehicle.

Task-4. Create a method to display all the properties of an object of the class.

Task-5. Additionally, you need to create two objects of the Vehicle class object that should
have a max speed of 200kph and mileage of 50000kmpl with five seating capacities, and
another car object should have a max speed of 180kph and 75000kmpl with four seating
capacities.

Here's the Python code fulfilling all the tasks:

class Vehicle:
"""
This class represents a vehicle with attributes and methods.
"""
# Task 2: Default color
default_color = "white"

def __init__(self, max_speed, mileage):


"""
This method initializes the Vehicle object with its max_speed and
mileage.
"""
self.max_speed = max_speed
self.mileage = mileage
self.seating_capacity = None # Initially seating capacity is unknown
self.color = Vehicle.default_color # Use default color

def set_seating_capacity(self, capacity):


"""
This method assigns seating capacity to the vehicle.
"""
self.seating_capacity = capacity

def display_details(self):
"""
This method displays all the properties of the vehicle object.
"""
print(f"Make: {self.__class__.__name__}") # Get class name for generic
output
print(f"Model: {self.model} (if defined)") # Model attribute can be
added later
print(f"Year: {self.year} (if defined)") # Year attribute can be added
later
print(f"Color: {self.color}")
print(f"Max Speed: {self.max_speed} kph")
print(f"Mileage: {self.mileage} kmpl")
print(f"Seating Capacity: {self.seating_capacity}" if
self.seating_capacity else "Seating capacity not set")
print("-" * 30) # Separator for better readability

# Task 5: Create objects with different attributes


car1 = Vehicle(200, 50000)
car1.model = "Sedan" # Add model attribute (optional)
car1.year = 2023 # Add year attribute (optional)
car1.set_seating_capacity(5)

car2 = Vehicle(180, 75000)


car2.model = "SUV" # Add model attribute (optional)
car2.year = 2022 # Add year attribute (optional)
car2.set_seating_capacity(4)

# Display details of each car


car1.display_details()
car2.display_details()

2. Write a program find Euclidean distance between two pints in a three-dimensional


space using class and objects. Class called point consists of a constructor (init()) and
two functions # distancefromorgin() and distance().

Here's the Python code for a Point class that calculates Euclidean distance in 3D space:

class Point:
"""
This class represents a point in 3D space with coordinates.
"""

def __init__(self, x, y, z):


"""
This method initializes the Point object with its x, y, and z
coordinates.
"""
self.x = x
self.y = y
self.z = z

def distance_from_origin(self):
"""
This method calculates the Euclidean distance of the point from the
origin (0, 0, 0).
"""
return (self.x**2 + self.y**2 + self.z**2) ** 0.5

def distance(self, other):


"""
This method calculates the Euclidean distance between this point and
another point.
"""
if not isinstance(other, Point):
raise TypeError("Argument must be a Point object")
return ((self.x - other.x)**2 + (self.y - other.y)**2 + (self.z -
other.z)**2) ** 0.5

# Example usage
point1 = Point(1, 2, 3)
point2 = Point(4, 5, 6)

# Distance from origin


distance1 = point1.distance_from_origin()
distance2 = point2.distance_from_origin()

# Distance between points


distance_between = point1.distance(point2)

print(f"Distance of point1 from origin: {distance1:.2f}")


print(f"Distance of point2 from origin: {distance2:.2f}")
print(f"Distance between point1 and point2: {distance_between:.2f}")

3. (i). Create a base class called “Animal” and two subclasses, “Dog” and “Cat.” Add
methods and attributes specific to each subclass.
(ii). Create a Bus child class that inherits from the Vehicle class. The default fare charge
of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an
extra 10% on full fare as a maintenance charge. So total fare for bus instance will
become the final amount = total fare + 10% of the total fare.
Note: The bus seating capacity is 50. so the final fare amount should be 5500. You
need to override the fare() method of a Vehicle class in Bus class.

Here's the Python code demonstrating inheritance with animals and vehicles:

class Animal:
"""
This class represents a base animal with a name attribute.
"""

def __init__(self, name):


self.name = name

def speak(self):
"""
This method defines generic animal sound (can be overridden in
subclasses).
"""
print("Animal sound")

class Dog(Animal):
"""
This class represents a Dog subclass inheriting from Animal.
"""

def __init__(self, name, breed):


super().__init__(name) # Call parent class constructor
self.breed = breed

def speak(self):
"""
Overrides the speak method for Dog sound.
"""
print(f"{self.name} barks!")

class Cat(Animal):
"""
This class represents a Cat subclass inheriting from Animal.
"""

def __init__(self, name, fur_color):


super().__init__(name) # Call parent class constructor
self.fur_color = fur_color

def speak(self):
"""
Overrides the speak method for Cat sound.
"""
print(f"{self.name} meows!")

class Vehicle:
"""
This class represents a base vehicle with attributes and a fare
calculation method.
"""
default_fare_rate = 100

def __init__(self, seating_capacity):


self.seating_capacity = seating_capacity

def fare(self):
"""
This method calculates the base fare based on seating capacity.
"""
return self.seating_capacity * self.default_fare_rate

class Bus(Vehicle):
"""
This class represents a Bus subclass inheriting from Vehicle and overrides
fare calculation.
"""

def __init__(self):
super().__init__(seating_capacity=50) # Set default seating capacity

def fare(self):
"""
Overrides the fare method to include a 10% maintenance charge for Bus.
"""
base_fare = super().fare() # Call parent class fare calculation
maintenance_charge = base_fare * 0.1
return base_fare + maintenance_charge

# Animal examples
dog1 = Dog("Buddy", "Labrador")
cat1 = Cat("Whiskers", "Black")

dog1.speak()
cat1.speak()

# Vehicle examples
car = Vehicle(4)
bus = Bus()

print(f"Car fare: {car.fare()}") # Output: Car fare: 400


print(f"Bus fare: {bus.fare()}") # Output: Bus fare: 5500 (base fare + 10%
maintenance charge)

4. Create a function that takes an animal object as input and calls its “sound” method. Test
it with both a dog and a cat object and utilize base class called “Animal” and two
subclasses, “Dog” and “Cat.” Add methods and attributes specific to each subclass.

class Animal:
"""
This class represents a base animal with a name attribute.
"""

def __init__(self, name):


self.name = name

def speak(self):
"""
This method defines generic animal sound (can be overridden in
subclasses).
"""
print("Animal sound")

class Dog(Animal):
"""
This class represents a Dog subclass inheriting from Animal.
"""

def __init__(self, name, breed):


super().__init__(name) # Call parent class constructor
self.breed = breed

def speak(self):
"""
Overrides the speak method for Dog sound.
"""
print(f"{self.name} barks!")

class Cat(Animal):
"""
This class represents a Cat subclass inheriting from Animal.
"""

def __init__(self, name, fur_color):


super().__init__(name) # Call parent class constructor
self.fur_color = fur_color

def speak(self):
"""
Overrides the speak method for Cat sound.
"""
print(f"{self.name} meows!")

def make_animal_sound(animal):
"""
This function takes an animal object as input and calls its speak method.
"""
if not isinstance(animal, Animal):
raise TypeError("Argument must be an Animal object")
animal.speak()

# Create animal objects


dog1 = Dog("Buddy", "Labrador")
cat1 = Cat("Whiskers", "Ginger")

# Make animal sounds using the make_animal_sound function


make_animal_sound(dog1)
make_animal_sound(cat1)

# Trying with a non-animal object (will raise TypeError)


try:
make_animal_sound("Not an Animal")
except TypeError as e:
print(f"Error: {e}")

5. Create three classes, “Person,” “Employee,” and “Student.” Use multiple inheritance to
create a class “PersonInfo” that inherits from both “Employee” and “Student.” Add
attributes and methods specific to each class.

class Person:
"""
This class represents a base Person with a name attribute.
"""

def __init__(self, name):


self.name = name

def introduce(self):
"""
This method introduces the person by name.
"""
print(f"Hello, my name is {self.name}.")

class Employee:
"""
This class represents an Employee with a company and salary attribute.
"""

def __init__(self, company, salary):


self.company = company
self.salary = salary

def work(self):
"""
This method simulates an employee working.
"""
print(f"{self.name} is working at {self.company}.")

class Student:
"""
This class represents a Student with a school and program attribute.
"""

def __init__(self, school, program):


self.school = school
self.program = program

def study(self):
"""
This method simulates a student studying.
"""
print(f"{self.name} is studying {self.program} at {self.school}.")

class PersonInfo(Person, Employee, Student):


"""
This class inherits from both Person, Employee, and Student using multiple
inheritance.
"""

def __init__(self, name, company, salary, school, program):


# Here, we can explicitly call the constructors of the parent classes
# to ensure proper initialization. This might be necessary depending on
the
# parent class constructors' logic.
Person.__init__(self, name)
Employee.__init__(self, company, salary)
Student.__init__(self, school, program)

# You can add additional methods specific to PersonInfo here

# Create objects and test methods


person1 = Person("Alice")
employee1 = Employee("Tech Company", 100000)
student1 = Student("University", "Computer Science")
person_info1 = PersonInfo("Bob", "Finance Company", 80000, "Business
School", "MBA")

person1.introduce()
employee1.work()
student1.study()
person_info1.introduce() # Inherited from Person
person_info1.work() # Inherited from Employee (method resolution order)
person_info1.study() # Inherited from Student (method resolution order)

6. Create an abstract base class called “Shape” with an abstract method called “area.”
Implement two subclasses, “Circle” and “Rectangle,” that inherit from “Shape” and
provide their own implementations of the “area” method.

Here's the Python code for an abstract base class Shape and subclasses Circle and
Rectangle :

from abc import ABC, abstractmethod

class Shape(ABC):
"""
This class represents an abstract base class for shapes with an abstract
area method.
"""

@abstractmethod
def area(self):
"""
This abstract method calculates the area of the shape. It must be
implemented by subclasses.
"""
pass

class Circle(Shape):
"""
This class represents a Circle subclass inheriting from Shape and
implementing the area method.
"""
def __init__(self, radius):
self.radius = radius

def area(self):
"""
This method calculates the area of the circle.
"""
return 3.14159 * self.radius**2

class Rectangle(Shape):
"""
This class represents a Rectangle subclass inheriting from Shape and
implementing the area method.
"""

def __init__(self, length, width):


self.length = length
self.width = width

def area(self):
"""
This method calculates the area of the rectangle.
"""
return self.length * self.width

# Example usage
circle1 = Circle(5)
rectangle1 = Rectangle(4, 3)

print(f"Circle area: {circle1.area():.2f}")


print(f"Rectangle area: {rectangle1.area():.2f}")

# Trying to create a Shape object directly will raise an error (abstract


class)
try:
shape1 = Shape()
except TypeError as e:
print(f"Error: {e}")

7. Create a class called “MathUtils” with class methods for calculating the factorial of a
number and a static method to check if a number is even.

class MathUtils:
"""
This class provides mathematical utility functions.
"""

@classmethod
def factorial(cls, number):
"""
This class method calculates the factorial of a number.
"""
if number < 0:
raise ValueError("Factorial is not defined for negative numbers")
if number == 0:
return 1
factorial = 1
for i in range(2, number + 1):
factorial *= i
return factorial

@staticmethod
def is_even(number):
"""
This static method checks if a number is even.
"""
return number % 2 == 0

# Example usage
num = 5
factorial_result = MathUtils.factorial(num)
is_even_result = MathUtils.is_even(num)

print(f"Factorial of {num}: {factorial_result}")


print(f"Is {num} even: {is_even_result}")

8. Write python code create classes for “Author” and “Book.” The “Book” class should
have an “Author” object as an attribute, demonstrating composition.

Here's the Python code for Author and Book classes demonstrating composition:

class Author:
"""
This class represents an Author with name and email attributes.
"""

def __init__(self, name, email):


self.name = name
self.email = email

def __str__(self):
"""
This method defines a string representation of the Author object for
better printing.
"""
return f"Author: {self.name} ({self.email})"
class Book:
"""
This class represents a Book with title, year, and an Author object as an
attribute.
"""

def __init__(self, title, year, author):


self.title = title
self.year = year
self.author = author

def __str__(self):
"""
This method defines a string representation of the Book object including
author details.
"""
return f"Book: {self.title} ({self.year}) by {self.author}"

# Example usage
author1 = Author("John Doe", "[email protected]")
book1 = Book("The Great Gatsby", 1925, author1)

print(f"Book details: {book1}")

9. Write python code to concatenate the two given strings using Operator Overloading.

Sure, here's the Python code to concatenate two strings using operator overloading:

class String:
"""
This class represents a simple string wrapper for string concatenation
using operator overloading.
"""

def __init__(self, value):


self.value = value

def __add__(self, other):


"""
This method overloads the + operator for String objects to perform
concatenation.
"""
if not isinstance(other, String):
raise TypeError("Can only concatenate String objects")
return String(self.value + other.value)
def __str__(self):
"""
This method defines a string representation of the String object.
"""
return self.value

# Example usage
str1 = String("Hello")
str2 = String(", World!")

concatenated_string = str1 + str2

print(concatenated_string) # Output: Hello, World!

10. Write python code to create a class called “Calculator” with methods for addition,
subtraction, multiplication, and division. Handle exceptions like division by zero
gracefully and raise custom exceptions when needed.

Here's the Python code for a Calculator class with exception handling:

class Calculator:
"""
This class represents a simple calculator with methods for basic
operations.
"""

def add(self, num1, num2):


"""
This method performs addition of two numbers.
"""
return num1 + num2

def subtract(self, num1, num2):


"""
This method performs subtraction of two numbers.
"""
return num1 - num2

def multiply(self, num1, num2):


"""
This method performs multiplication of two numbers.
"""
return num1 * num2

def divide(self, num1, num2):


"""
This method performs division of two numbers, handling division by zero.
"""
if num2 == 0:
raise ZeroDivisionError("Division by zero is not allowed")
return num1 / num2

# Example usage
calculator = Calculator()

result_add = calculator.add(5, 3)
result_subtract = calculator.subtract(10, 2)
result_multiply = calculator.multiply(4, 6)

try:
result_divide = calculator.divide(12, 0) # Will raise ZeroDivisionError
except ZeroDivisionError as e:
result_divide = "Error: " + str(e)

print(f"Addition result: {result_add}")


print(f"Subtraction result: {result_subtract}")
print(f"Multiplication result: {result_multiply}")
print(f"Division result: {result_divide}")

11. Write python code to create classes for “Department” and “Employee.” Use aggregation
to represent that an Employee belongs to a Department. Implement methods to add
employees to a department and calculate the average salary of employees in a
department.

class Employee:
"""
This class represents an Employee with name and salary attributes.
"""

def __init__(self, name, salary):


self.name = name
self.salary = salary
self.department = None # Department object will be assigned later

def __str__(self):
"""
This method defines a string representation of the Employee object.
"""
return f"Employee: {self.name} (Salary: ${self.salary:.2f})"

class Department:
"""
This class represents a department with a name attribute and a list of
employees.
"""

def __init__(self, name):


self.name = name
self.employees = [] # List to store employee objects

def add_employee(self, employee):


"""
This method adds an employee object to the department's employee list.
"""
self.employees.append(employee)
employee.department = self # Assign department to the employee
(aggregation)

def calculate_average_salary(self):
"""
This method calculates the average salary of all employees in the
department.
"""
if not self.employees:
return 0 # Handle case with no employees
total_salary = sum(employee.salary for employee in self.employees)
return total_salary / len(self.employees)

def __str__(self):
"""
This method defines a string representation of the Department object.
"""
return f"Department: {self.name}"

# Example usage
department1 = Department("Engineering")
employee1 = Employee("Alice", 80000)
employee2 = Employee("Bob", 95000)

department1.add_employee(employee1)
department1.add_employee(employee2)

average_salary = department1.calculate_average_salary()

print(f"{department1}") # Print department name


for employee in department1.employees:
print(employee) # Print employee details

print(f"Average salary in {department1.name} department:


${average_salary:.2f}")
12. Create a base class called “Vehicle” with a method called “drive.” Implement two
subclasses, “Car” and “Bicycle,” that inherit from “Vehicle” and override the “drive”
method with their own implementations.

Here's the Python code for a base class Vehicle with subclasses Car and Bicycle
demonstrating method overriding:

class Vehicle:
"""
This class represents a base vehicle with a drive method.
"""

def drive(self):
"""
This method provides a generic drive message for vehicles.
"""
print("The vehicle is moving.")

class Car(Vehicle):
"""
This class represents a Car subclass inheriting from Vehicle and
overriding the drive method.
"""

def drive(self):
"""
This method overrides the drive method with a specific car driving
message.
"""
print("The car is driving on the road.")

class Bicycle(Vehicle):
"""
This class represents a Bicycle subclass inheriting from Vehicle and
overriding the drive method.
"""

def drive(self):
"""
This method overrides the drive method with a specific bicycle driving
message.
"""
print("The bicycle is pedaling forward.")

# Example usage
car = Car()
bicycle = Bicycle()

car.drive()
bicycle.drive()

13. Write python code to perform the following Lamda function below:
(i) Map()
(ii) filter()
(iii) lambda function to calculate grades for a list of scores.
(iv) List Comprehensions.
(v) calculates the factorial of a number using a recursive lambda function.

i) Map()

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers) # Map the square function to
each number

# Print the squared numbers (iterator object, convert to list for printing)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]

ii) filter()

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers) # Filter even numbers

# Print the even numbers (iterator object, convert to list for printing)
print(list(even_numbers)) # Output: [2, 4, 6]

iii) Lambda for grades

scores = [85, 92, 78, 65, 98]

def calculate_grade(score):
"""
This function calculates the grade based on a score using a lambda
function.
"""
grade_scale = {
90: "A",
80: "B",
70: "C",
60: "D",
below_60: "F"
}
return grade_scale.get(score // 10, grade_scale[below_60])
grades = list(map(calculate_grade, scores))
print(f"Grades: {grades}") # Output: Grades: ['B', 'A', 'C', 'D', 'A']

iv) List Comprehensions

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers] # Square each number using list
comprehension

print(f"Squared numbers: {squared_numbers}") # Output: Squared numbers: [1,


4, 9, 16, 25]

v) Recursive lambda for factorial

factorial = lambda n: n * factorial(n - 1) if n > 1 else 1 # Recursive


lambda for factorial

# Calculate factorial of 5
result = factorial(5)
print(f"Factorial of 5: {result}") # Output: Factorial of 5: 120

14. (i). Write python GUI application is developed for computing loan payments. The code
consists of the following steps:
1.Design the user interface consisting of labels using Label( ), text entry boxes using
Entry( ), and a button using Button( ). 2.Process the event. When the button is clicked,
the program invokes a callback functions, using getMonthlyPayment( ) to obtain the
user input for the interest rate, number of years, and loan amount from the text entries.
The monthly and total payments are computed using computePayment( ) and displayed
in the labels.

Here's the Python code for a GUI loan calculator application using Tkinter:

import tkinter as tk

def compute_payment():
"""
This function calculates the monthly and total loan payments based on user
input.
"""
try:
# Get user input from entry fields
loan_amount = float(loan_amount_entry.get())
annual_interest_rate = float(interest_rate_entry.get()) / 100
loan_term_years = float(loan_term_years_entry.get())
# Calculate monthly interest rate
monthly_interest_rate = annual_interest_rate / 12

# Calculate number of payments


number_of_payments = int(loan_term_years * 12)

# Calculate monthly payment using loan formula (assuming equal payments)


monthly_payment = loan_amount * (monthly_interest_rate * (1 +
monthly_interest_rate) ** number_of_payments) / ((1 + monthly_interest_rate)
** number_of_payments - 1)

# Calculate total payment


total_payment = monthly_payment * number_of_payments

# Update labels with formatted results


monthly_payment_label.config(text=f"Monthly Payment:
${monthly_payment:.2f}")
total_payment_label.config(text=f"Total Payment: ${total_payment:.2f}")
except ValueError:
# Handle invalid input (non-numeric values)
monthly_payment_label.config(text="Error: Please enter valid numbers")
total_payment_label.config(text="")

# Create the main window


root = tk.Tk()
root.title("Loan Calculator")

# Labels for loan amount, interest rate, loan term, and payment results
loan_amount_label = tk.Label(root, text="Loan Amount:")
loan_amount_label.pack()

interest_rate_label = tk.Label(root, text="Annual Interest Rate (%):")


interest_rate_label.pack()

loan_term_years_label = tk.Label(root, text="Loan Term (Years):")


loan_term_years_label.pack()

monthly_payment_label = tk.Label(root)
monthly_payment_label.pack()

total_payment_label = tk.Label(root)
total_payment_label.pack()

# Entry fields for user input


loan_amount_entry = tk.Entry(root)
loan_amount_entry.pack()

interest_rate_entry = tk.Entry(root)
interest_rate_entry.pack()
loan_term_years_entry = tk.Entry(root)
loan_term_years_entry.pack()

# Button to trigger the calculation


calculate_button = tk.Button(root, text="Calculate Payment",
command=compute_payment)
calculate_button.pack()

# Run the main event loop


root.mainloop()

15. Creating a popup menu is similar to creating a regular menu. First, you create an
instance of Popup menu using Menu( ), and then you can add items to it using
menu.add_command( ). Finally, you bind a widget with an event to pop up the menu.
Popup menu commands are used to perform actions to be displayed in a canvas which
is created using canvas( ). The canvas widget is used to add the structured graphics to
the python application. It is used to display text, images, graph and plots to the python
application. The menu items use callback functions to instruct the canvas to perform
actions. In code, a popup menu is displayed by clicking the right mouse button followed
by binding it with the canvas using canvas.bind( ). Each item in the popup menu is
selected to perform the corresponding arithmetic operations. The inputs are obtained in
two textboxes and the output is displayed in one textbox.

Here's the Python code for a GUI application with a popup menu for arithmetic operations
using Tkinter:

import tkinter as tk

def create_popup_menu(root, canvas):


"""
This function creates a popup menu for arithmetic operations and binds it
to the canvas.
"""
popup_menu = tk.Menu(root, tearoff=0) # Create popup menu with tearoff
disabled

# Add menu items for operations


popup_menu.add_command(label="Add", command=lambda:
perform_operation("+"))
popup_menu.add_command(label="Subtract", command=lambda:
perform_operation("-"))
popup_menu.add_command(label="Multiply", command=lambda:
perform_operation("*"))
popup_menu.add_command(label="Divide", command=lambda:
perform_operation("/"))
# Bind the popup menu to right-click on the canvas
def show_menu(event):
popup_menu.post(event.x_root, event.y_root) # Position the menu at
click coordinates
canvas.bind("<Button-3>", show_menu) # Bind right-click to show menu

def perform_operation(operator):
"""
This function retrieves input from textboxes, performs the selected
operation, and displays the result.
"""
try:
num1 = float(number1_entry.get())
num2 = float(number2_entry.get())
if operator == "/" and num2 == 0:
raise ZeroDivisionError("Division by zero is not allowed")
result = eval(f"{num1}{operator}{num2}") # Use eval for simple
calculations
result_label.config(text=f"Result: {result:.2f}") # Display formatted
result
except (ValueError, ZeroDivisionError) as e:
result_label.config(text=f"Error: {str(e)}") # Display error message

# Create the main window


root = tk.Tk()
root.title("Arithmetic Calculator")

# Labels for numbers and result


number1_label = tk.Label(root, text="Number 1:")
number1_label.pack()

number2_label = tk.Label(root, text="Number 2:")


number2_label.pack()

result_label = tk.Label(root, text="Result:")


result_label.pack()

# Entry fields for number input


number1_entry = tk.Entry(root)
number1_entry.pack()

number2_entry = tk.Entry(root)
number2_entry.pack()

# Canvas widget (not used for drawing in this example, just for binding)
canvas = tk.Canvas(root, width=100, height=50)
canvas.pack()

# Create and bind the popup menu


create_popup_menu(root, canvas)

# Run the main event loop


root.mainloop()

16. Program to read and display an RGB color image and convert it into grayscale,
negative and edge images.

Here's the Python code using OpenCV to achieve the desired functionalities:

import cv2
import numpy as np

def display_image(window_name, image):


"""
This function displays an image in a named window.
"""
cv2.imshow(window_name, image)
cv2.waitKey(0) # Wait for a key press to close the window
cv2.destroyAllWindows() # Close all windows

def convert_to_grayscale(image):
"""
This function converts an RGB image to grayscale.
"""
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

def convert_to_negative(image):
"""
This function converts an RGB image to its negative.
"""
return 255 - image

def detect_edges(image):
"""
This function detects edges in an image using Canny edge detection.
"""
# Convert to grayscale if needed (assuming RGB input)
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Canny edge detection
return cv2.Canny(grayscale_image, 50, 150)

# Read the image in BGR format (OpenCV default)


image = cv2.imread("your_image.jpg")

# Check if image read successfully


if image is None:
print("Error: Could not read image file")
exit()

# Display the original image


display_image("Original Image", image)

# Convert to grayscale
grayscale_image = convert_to_grayscale(image.copy()) # Copy to avoid
modifying original
display_image("Grayscale Image", grayscale_image)

# Convert to negative
negative_image = convert_to_negative(image.copy())
display_image("Negative Image", negative_image)

# Detect edges
edge_image = detect_edges(image.copy())
display_image("Edge Image", edge_image)

print("Image processing completed. Press any key to exit.")


cv2.waitKey(0)

You might also like