0% found this document useful (0 votes)
86 views54 pages

New Lab Manual Final

This Python program implements a real-time automobile management system using sets. It allows adding and removing models from a catalog set, adding vehicles to an inventory set, and selling vehicles from inventory. Customer preferences are tracked in a preferences set and common preferences can be analyzed. The main program loop prompts the user to add/remove models, add to inventory, sell vehicles, view preferences, and find common preferences until exiting.

Uploaded by

playerpubglite4
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)
86 views54 pages

New Lab Manual Final

This Python program implements a real-time automobile management system using sets. It allows adding and removing models from a catalog set, adding vehicles to an inventory set, and selling vehicles from inventory. Customer preferences are tracked in a preferences set and common preferences can be analyzed. The main program loop prompts the user to add/remove models, add to inventory, sell vehicles, view preferences, and find common preferences until exiting.

Uploaded by

playerpubglite4
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/ 54

1.

a) Implementation of Library management using List

Aim:
This project aims to create a real-time library management system using lists in Python. The system
should allow users to perform various operations such as adding books, removing books, displaying available
books, checking out books, and returning books.

Algorithm:

1. Book Class:
o Create a Book class with attributes for title, author, and availability status.

2. Library Class:

o Create a Library class with methods for adding a book, removing a book, displaying
available books, checking out a book, and returning a book.

o Initialize an empty list to store books.

o Implement methods to manipulate the list of books based on user actions.

3. Main Function:

o Implement a main() function to interact with users through a menu-driven interface.

o Prompt users to choose from various options (add a book, remove a book, display
available books, check out a book, return a book, or exit).

Program

class Book:
def __init__(self, title, author):
self.title = title
self.author = author
self.available = True

def __str__(self):
return f"Title: {self.title}\nAuthor: {self.author}\nAvailable: {'Yes' if self.available else 'No'}"

class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
print("Book added successfully.")

def display_books(self):
if not self.books:
print("No books in the library.")
else:
for index, book in enumerate(self.books, start=1):
print(f"Book {index}:")
print(book)

def borrow_book(self, title):


for book in self.books:
if book.title.lower() == title.lower() and book.available:
book.available = False
print(f"{book.title} borrowed successfully.")
return
print("Book not found or not available.")

def return_book(self, title):


for book in self.books:
if book.title.lower() == title.lower() and not book.available:
book.available = True
print(f"{book.title} returned successfully.")
return
print("Book not found or already returned.")

def main():
library = Library()
while True:
print("\nLibrary Management System")
print("1. Add Book")
print("2. Display Books")
print("3. Borrow Book")
print("4. Return Book")
print("5. Exit")
choice = input("Enter your choice: ")

if choice == '1':
title = input("Enter book title: ")
author = input("Enter book author: ")
book = Book(title, author)
library.add_book(book)
elif choice == '2':
library.display_books()
elif choice == '3':
title = input("Enter book title to borrow: ")
library.borrow_book(title)
elif choice == '4':
title = input("Enter book title to return: ")
library.return_book(title)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please choose again.")

if __name__ == "__main__":
main()
Output:

Library Management System


1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 2
Book 1:
Title: Think Python
Author: Allen
Available: Yes
Book 2:
Title: Introduction to Data Science
Author: David
Available: Yes

Library Management System


1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 3
Enter book title to borrow: Think Python
Think Python borrowed successfully.

Library Management System


1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 2
Book 1:
Title: Think Python
Author: Allen
Available: No
Book 2:
Title: Introduction to Data Science
Author: David
Available: Yes

Library Management System


1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 3
Enter book title to borrow: Think Python
Book not found or not available.

Library Management System


1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 4
Enter book title to return: Think Python
Think Python returned successfully.
Library Management System
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 5
Exiting the program.

Result:
The Python program for Library stock management is executed, and the output is verified.
1b. Implementation of construction material management using list

Aim:
The Python program for construction materials aims to provide a tool for managing information
about various construction materials, including their names, quantities, and prices. This program enables
users to add new materials, update existing materials, and display the list of materials along with their
details.

Algorithm:
1. Start the program.
2. Initialize an empty dictionary or list to store information about construction materials.
3. Define functions/methods to perform the following operations:
4. Add a new material: Prompt the user to enter the name, quantity, and price of the material.
Add this information to the dictionary or list.
5. Update an existing material: Prompt the user to enter the name of the material to be updated.
If the material exists, allow the user to update its quantity and price.
6. Display materials: Iterate through the dictionary or list and print the details of each material.
7. Implement a loop to continuously prompt the user for choices until they choose to exit the
program.
8. Provide options for the user to add new materials, update existing materials, display the list of
materials, or exit the program.
9. End the program.

Program:
# Initialize an empty list to store construction materials
materials = []
def add_material(name, quantity, price_per_unit):
"""Add a new material to the list"""
material = (name, quantity, price_per_unit)
materials.append(material)
print(f"{name} added to the materials list.")
def update_material(name, quantity, price_per_unit):
"""Update an existing material in the list"""
for i, material in enumerate(materials):
if material[0] == name:
materials[i] = (name, quantity, price_per_unit)
print(f"{name} updated in the materials list.")
return
print(f"{name} not found in the materials list.")

def display_materials():
"""Display all materials in the list"""
if not materials:
print("No materials found.")
else:
print("Materials List:")
for material in materials:
print(f"Name: {material[0]}, Quantity: {material[1]}, Price Per Unit: {material[2]}")

# Main program loop


while True:
print("\nConstruction Materials Management System")
print("1. Add Material")
print("2. Update Material")
print("3. Display Materials")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == '1':
name = input("Enter material name: ")
quantity = int(input("Enter quantity: "))
price_per_unit = float(input("Enter price per unit: "))
add_material(name, quantity, price_per_unit)

elif choice == '2':


name = input("Enter material name to update: ")
quantity = int(input("Enter new quantity: "))
price_per_unit = float(input("Enter new price per unit: "))
update_material(name, quantity, price_per_unit)
elif choice == '3':
display_materials()

elif choice == '4':


print("Exiting program.")
break

else:
print("Invalid choice. Please enter a number between 1 and 4.")

Output:
Construction Materials Management System
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 1
Enter material name: cement
Enter quantity: 10
Enter price per unit: 100
cement added to the materials list.

Construction Materials Management System


1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 3
Materials List:
Name: cement, Quantity: 10, Price Per Unit: 100.0
Construction Materials Management System
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 1
Enter material name: steel
Enter quantity: 100
Enter price per unit: 2000
steel added to the materials list.

Construction Materials Management System


1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 2
Enter material name to update: cement
Enter new quantity: 5
Enter new price per unit: 105
cement updated in the materials list.

Construction Materials Management System


1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 3
Materials List:
Name: cement, Quantity: 5, Price Per Unit: 105.0
Name: steel, Quantity: 100, Price Per Unit: 2000.0
Construction Materials Management System
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 4
Exiting program.

Result:
The Python program for construction materials management is executed, and the output is verified.

2) a) Implementing real-time applications using Sets,


Aim:

The aim of the program is to simulate a basic management system for automobiles. It allows management of
a vehicle catalog, inventory, and analysis of customer preferences.

Algorithm:

1. Define a class Automobile with methods to manage the catalog, inventory, and customer preferences.
2. Implement methods to add and remove models from the catalog, add vehicles to the inventory, and
sell vehicles.
3. Implement methods to record and update customer preferences, as well as find common preferences
among customers.
4. In the main() function:
o Create an instance of Automobile.
o Populate initial data including catalog models, vehicles in inventory, and customer
preferences.
o Present a menu to the user with options to manage the catalog, inventory, analyze customer
preferences, or exit.
o Based on the user's choice, perform the corresponding actions using methods from the
Automobile class.

Program:
class Automobile:
def __init__(self):
self.catalog = set()
self.inventory = set()
self.customer_preferences = {}
def add_model_to_catalog(self, model):
self.catalog.add(model)
print(f"Model '{model}' added to the catalog.")
def remove_model_from_catalog(self, model):
if model in self.catalog:
self.catalog.remove(model)
print(f"Model '{model}' removed from the catalog.")
else:
print(f"Model '{model}' not found in the catalog.")
def display_catalog(self):
print("Vehicle Catalog:")
for model in self.catalog:
print("-", model)
def add_vehicle_to_inventory(self, vehicle):
self.inventory.add(vehicle)
print(f"Vehicle '{vehicle}' added to the inventory.")
def sell_vehicle(self, vehicle):
if vehicle in self.inventory:
self.inventory.remove(vehicle)
print(f"Vehicle '{vehicle}' sold.")
else:
print(f"Vehicle '{vehicle}' not found in the inventory.")
def display_inventory(self):
print("Current Inventory:")
for vehicle in self.inventory:
print("-", vehicle)
def add_customer_preference(self, customer, models):
self.customer_preferences[customer] = set(models)
print(f"Customer '{customer}' preferences recorded successfully.")
def update_customer_preference(self, customer, new_models):
if customer in self.customer_preferences:
self.customer_preferences[customer].update(new_models)
print(f"Customer '{customer}' preferences updated successfully.")
else:
print(f"Customer '{customer}' not found in the preferences.")
def common_preferences(self):
common_pref = set.intersection(*self.customer_preferences.values())
print("Common Customer Preferences:")
for model in common_pref:
print("-", model)
def main():
auto = Automobile()
# Populate initial data
auto.add_model_to_catalog("SUV")
auto.add_model_to_catalog("Sedan")
auto.add_model_to_catalog("Hatchback")
auto.add_model_to_catalog("Truck")
auto.add_vehicle_to_inventory("SUV-001")
auto.add_vehicle_to_inventory("Sedan-001")
auto.add_vehicle_to_inventory("Hatchback-001")
auto.add_vehicle_to_inventory("Truck-001")
auto.add_customer_preference("John", ["SUV", "Sedan"])
auto.add_customer_preference("Alice", ["SUV", "Hatchback"])
auto.add_customer_preference("Bob", ["Sedan", "Truck"])

# Main Menu
while True:
print("\nMenu:")
print("1. Vehicle Catalog Management")
print("2. Inventory Management")
print("3. Customer Preference Analysis")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
print("\nVehicle Catalog Management:")
auto.add_model_to_catalog(input("Enter new model to add: "))
auto.remove_model_from_catalog(input("Enter model to remove: "))
auto.display_catalog()
elif choice == '2':
print("\nInventory Management:")
auto.add_vehicle_to_inventory(input("Enter new vehicle to add to inventory: "))
auto.sell_vehicle(input("Enter vehicle sold: "))
auto.display_inventory()
elif choice == '3':
print("\nCustomer Preference Analysis:")
auto.add_customer_preference(input("Enter customer name: "),
input("Enter preferred models (comma-separated): ").split(','))
auto.update_customer_preference(input("Enter customer name to update preferences: "),
input("Enter new preferred models (comma-separated): ").split(','))
auto.common_preferences()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number from 1 to 4.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Vehicle Catalog Management
2. Inventory Management
3. Customer Preference Analysis
4. Exit
Enter your choice: 1

Vehicle Catalog Management:


Enter new model to add: 3
Model '3' added to the catalog.
Enter model to remove: track
Model 'track' not found in the catalog.
Vehicle Catalog:
- SUV
-3
- Hatchback
- Sedan
- Truck

Menu:
1. Vehicle Catalog Management
2. Inventory Management
3. Customer Preference Analysis
4. Exit
Enter your choice:

Result:
Thus, the implementation of Vehicle implementation are implemented and result was obtained

3)a) Implementing programs using Functions Factorial


Aim:
The aim of this program is to calculate the factorial of a given number using functions in Python. Factorial of
a non-negative integer nn, denoted as n!n!, is the product of all positive integers less than or equal to nn.

Algorithm:

1. Define a function named factorial that takes an integer parameter n.


2. Initialize a variable result to 1. This variable will store the factorial value.
3. Use a loop to iterate from 1 to n (inclusive).
4. Multiply result by the current value of the loop variable.
5. After the loop, return the value of result as the factorial of n.
6. In the main program:
o Prompt the user to input a number for which they want to calculate the factorial.
o Call the factorial function with the user input as argument and store the result.
o Print the factorial value.

Program:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i # Fix: Multiply 'result' by 'i', not assign 'i' to 'result'
return result

def main():
try:
num = int(input("Enter a non-negative integer: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")
except ValueError:
print("Invalid input. Please enter a valid integer.")

if __name__ == "__main__":
main()
Result:
Thus,the Implementing programs using Functions Factorial and result was obtained

3) b) Implementing programs using Functions using largest number in a list


Aim:
The aim of the aim of this program is to provide a simple and modular solution for finding the largest number
in a list, with robust error handling for user input.

Algorithm:

1. Define a function named find_largest that takes a list of numbers as input.


2. Initialize a variable largest to store the largest number found in the list. Set it initially to the first
element of the list.
3. Iterate through the list:
o For each element num in the list, compare it with the current value of largest.
o If num is greater than largest, update largest to num.
4. After iterating through the entire list, return the value of largest.
5. In the main program:
o Define a list of numbers.
o Call the find_largest function with the list as argument and store the result.
o Print the largest number found.

Program:
def find_largest(numbers):
if not numbers:
return None

max_number = numbers[0]
for num in numbers:
if num > max_number:
max_number = num
return max_number

def main():
try:
numbers = [int(x) for x in input("Enter numbers separated by space: ").split()]
largest = find_largest(numbers)
if largest is not None:
print(f"The largest number in the list is {largest}.")
else:
print("No numbers were provided.")
except ValueError:
print("Invalid input. Please enter numbers separated by space.")

if __name__ == "__main__":
main()

output

Result:
Thus the implementation of the programs using Functions using largest number in a list and result was
obtained

3) C) Implementing programs using Functions using area of shape


Aim
The aim of the provided code is to create a program that allows users to calculate the area of different geometric
shapes (circle, rectangle, or triangle) based on their choices.

Algorithm:

1. Define functions for calculating the area of different shapes: square_area, rectangle_area, and
circle_area.
2. square_area function:
o Takes the length of a side as input.
o Calculates the area using the formula: area = side * side.
o Returns the calculated area.
3. rectangle_area function:
o Takes the length and width of the rectangle as input.
o Calculates the area using the formula: area = length * width.
o Returns the calculated area.
4. circle_area function:
o Takes the radius of the circle as input.
o Calculates the area using the formula: area = π * radius^2.
o Returns the calculated area.
5. In the main program:
o Prompt the user to choose a shape for which they want to calculate the area.
o Based on the user's choice, prompt for necessary dimensions.
o Call the respective function to calculate the area.

Program:
import math

def circle_area(radius):
return math.pi * radius**2

def rectangle_area(length, width):


return length * width

def triangle_area(base, height):


return 0.5 * base * height
def main():
print("Calculate Area of Shapes:")
print("1. Circle")
print("2. Rectangle")
print("3. Triangle")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
try:
radius = float(input("Enter the radius of the circle: "))
print(f"The area of the circle is {circle_area(radius)}.")
except ValueError:
print("Invalid input. Please enter a numeric value for the radius.")
elif choice == '2':
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
print(f"The area of the rectangle is {rectangle_area(length, width)}.")
except ValueError:
print("Invalid input. Please enter numeric values for length and width.")
elif choice == '3':
try:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
print(f"The area of the triangle is {triangle_area(base, height)}.")
except ValueError:
print("Invalid input. Please enter numeric values for base and height.")
else:
print("Invalid choice. Please enter 1, 2, or 3.")

if __name__ == "__main__":
main()

Output

Result:
Thus the program that allows users to calculate the area of different geometric shapes (circle, rectangle, or
triangle) based on their choices and result was obtained

STRING FUNCTIONS USING PYTHON


Aim: Implement programs using strings to perform various operations such as reversing a string, checking
if a string is a palindrome, counting characters in a string, and replacing characters in a string.

Algorithm:

1. Implement functions for each operation: reverse a string, check for palindrome, count characters, and
replace characters.
2. For reversing a string, use slicing or iteration.
3. For checking palindrome, compare the string with its reverse.
4. For counting characters, iterate through the string and maintain a count for each character.
5. For replacing characters, iterate through the string and replace the desired characters.
6. Display appropriate outputs for each operation.

Program:
# Function to reverse a string
def reverse_string(string):
return string[::-1]

# Function to check if a string is palindrome


def is_palindrome(string):
return string == string[::-1]

# Function to count characters in a string


def count_characters(string):
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1
return char_count

# Function to replace characters in a string


def replace_characters(string, old_char, new_char):
return string.replace(old_char, new_char)

def main():
while True:
print("\nMenu:")
print("1. Reverse a string")
print("2. Check if a string is palindrome")
print("3. Count characters in a string")
print("4. Replace characters in a string")
print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':
string = input("Enter a string: ")
print("Reversed string:", reverse_string(string))
elif choice == '2':
string = input("Enter a string: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
elif choice == '3':
string = input("Enter a string: ")
char_count = count_characters(string)
print("Character count:")
for char, count in char_count.items():
print(char, ":", count)
elif choice == '4':
string = input("Enter a string: ")
old_char = input("Enter character to replace: ")
new_char = input("Enter new character: ")
print("Modified string:", replace_characters(string, old_char, new_char))
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Output:
Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 1
Enter a string: hello
Reversed string: olleh

Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 2
Enter a string: radar
The string is a palindrome.

Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 3
Enter a string: hello
Character count:
h:1
e:1
l:2
o:1

Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 4
Enter a string: hello
Enter character to replace: l
Enter new character: z
Modified string: hezzo

Menu:
1. Reverse a string
2. Check if a string is palindrome
3. Count characters in a string
4. Replace characters in a string
5. Exit
Enter your choice: 5
Exiting program.

Result:

Thus the Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters) and result was obtained.

Program for File using Python


Aim: Implement a real-time/technical application using file handling to perform operations such as copying
content from one file to another, counting the number of words in a file, and finding the longest word in a
file.

Algorithm:

1. Define functions for each operation: copy content from one file to another, count words, and find the
longest word.
2. For copying content, open the source file in read mode and the destination file in write mode, then
read content from the source file and write it to the destination file.
3. For counting words, read the content from the file and split it into words using whitespace as a
delimiter. Count the number of words obtained.
4. For finding the longest word, split the content into words and iterate through them, keeping track of
the longest word encountered.
5. Display appropriate outputs for each operation.

Program:

# Function to copy content from one file to another


def copy_file(source_file, destination_file):
with open(source_file, 'r') as source:
with open(destination_file, 'w') as destination:
destination.write(source.read())
print("Content copied successfully.")

# Function to count words in a file


def count_words(file_name):
with open(file_name, 'r') as file:
content = file.read()
word_count = len(content.split())
return word_count

# Function to find the longest word in a file


def longest_word(file_name):
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
longest = max(words, key=len)
return longest

def main():
while True:
print("\nMenu:")
print("1. Copy content from one file to another")
print("2. Count words in a file")
print("3. Find the longest word in a file")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':
source_file = input("Enter source file name: ")
destination_file = input("Enter destination file name: ")
copy_file(source_file, destination_file)
elif choice == '2':
file_name = input("Enter file name: ")
print("Number of words in the file:", count_words(file_name))
elif choice == '3':
file_name = input("Enter file name: ")
print("Longest word in the file:", longest_word(file_name))
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 1
Enter source file name: source.txt
Enter destination file name: destination.txt
Content copied successfully.

Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 2
Enter file name: destination.txt
Number of words in the file: 9

Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 3
Enter file name: destination.txt
Longest word in the file: successfully.
Menu:
1. Copy content from one file to another
2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your choice: 4
Exiting program.

Result:
Thus the Implementing real-time/technical applications using File handling. (copy from one file toanother,
word count, longest word) result was obtained

Program for Exception Handling

Aim:
Implement real-time/technical applications using exception handling to handle divide by zero errors, validate
voter's age, and validate student mark ranges.

Algorithm:

1. Define functions for each operation: division with error handling, voter's age validation, and student
mark range validation.
2. Use try-except blocks to catch specific exceptions raised during the execution of operations.
3. Implement logic to check if the input satisfies the conditions (e.g., age >= 18 for voting, marks within
a valid range).
4. Raise custom exceptions with meaningful error messages when input does not meet the criteria.
5. Display appropriate outputs or error messages based on the result of exception handling.

Program:
# Function to handle division with error handling
def divide(dividend, divisor):
try:
result = dividend / divisor
return result
except ZeroDivisionError:
raise ZeroDivisionError("Error: Division by zero is not allowed.")

# Function to validate voter's age


def validate_voter_age(age):
try:
if age < 18:
raise ValueError("Error: Voter must be 18 years or older.")
else:
print("Voter's age is valid.")
except ValueError as ve:
print(ve)

# Function to validate student mark range


def validate_mark_range(mark):
try:
if mark < 0 or mark > 100:
raise ValueError("Error: Mark should be between 0 and 100.")
else:
print("Student mark is within the valid range.")
except ValueError as ve:
print(ve)

def main():
while True:
print("\nMenu:")
print("1. Divide numbers with error handling")
print("2. Validate voter's age")
print("3. Validate student mark range")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':
try:
dividend = float(input("Enter dividend: "))
divisor = float(input("Enter divisor: "))
print("Result:", divide(dividend, divisor))
except ValueError:
print("Error: Please enter valid numeric values.")
elif choice == '2':
try:
age = int(input("Enter voter's age: "))
validate_voter_age(age)
except ValueError:
print("Error: Please enter a valid age.")
elif choice == '3':
try:
mark = float(input("Enter student mark: "))
validate_mark_range(mark)
except ValueError:
print("Error: Please enter a valid mark.")
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()

Output:
Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 1
Enter dividend: 10
Enter divisor: 0
Error: Division by zero is not allowed.

Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 2
Enter voter's age: 16
Error: Voter must be 18 years or older.

Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 3
Enter student mark: 110
Error: Mark should be between 0 and 100.

Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 1
Enter dividend: 20
Enter divisor: abc
Error: Please enter valid numeric values.

Menu:
1. Divide numbers with error handling
2. Validate voter's age
3. Validate student mark range
4. Exit
Enter your choice: 4
Exiting program.

Result:
Thus, the Implementing real-time/technical applications using Exception handling.

Program using Exception Handling

Aim:
To Implement real-time/technical applications using exception handling to handle divide by zero errors,
validate voter's age, and validate student mark ranges.

Algorithm:

1. Define functions for each operation: division with error handling, voter's age validation, and student
mark range validation.
2. Use try-except blocks to catch specific exceptions raised during the execution of operations.
3. Implement logic to check if the input satisfies the conditions (e.g., age >= 18 for voting, marks within
a valid range).
4. Raise custom exceptions with meaningful error messages when input does not meet the criteria.
5. Display appropriate outputs or error messages based on the result of exception handling.

Program:

# Function to handle division with error handling

def divide(dividend, divisor):

try:

result = dividend / divisor

return result

except ZeroDivisionError:

raise ZeroDivisionError("Error: Division by zero is not allowed.")

# Function to validate voter's age

def validate_voter_age(age):

try:

if age < 18:

raise ValueError("Error: Voter must be 18 years or older.")

else:

print("Voter's age is valid.")

except ValueError as ve:

print(ve)
# Function to validate student mark range

def validate_mark_range(mark):

try:

if mark < 0 or mark > 100:

raise ValueError("Error: Mark should be between 0 and 100.")

else:

print("Student mark is within the valid range.")

except ValueError as ve:

print(ve)

def main():

while True:

print("\nMenu:")

print("1. Divide numbers with error handling")

print("2. Validate voter's age")

print("3. Validate student mark range")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':

try:

dividend = float(input("Enter dividend: "))

divisor = float(input("Enter divisor: "))

print("Result:", divide(dividend, divisor))

except ValueError:

print("Error: Please enter valid numeric values.")

elif choice == '2':


try:

age = int(input("Enter voter's age: "))

validate_voter_age(age)

except ValueError:

print("Error: Please enter a valid age.")

elif choice == '3':

try:

mark = float(input("Enter student mark: "))

validate_mark_range(mark)

except ValueError:

print("Error: Please enter a valid mark.")

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Output:

Menu:

1. Divide numbers with error handling

2. Validate voter's age

3. Validate student mark range

4. Exit

Enter your choice: 1

Enter dividend: 10
Enter divisor: 0

Error: Division by zero is not allowed.

Menu:

1. Divide numbers with error handling

2. Validate voter's age

3. Validate student mark range

4. Exit

Enter your choice: 2

Enter voter's age: 16

Error: Voter must be 18 years or older.

Menu:

1. Divide numbers with error handling

2. Validate voter's age

3. Validate student mark range

4. Exit

Enter your choice: 3

Enter student mark: 110

Error: Mark should be between 0 and 100.

Menu:

1. Divide numbers with error handling

2. Validate voter's age

3. Validate student mark range

4. Exit

Enter your choice: 1

Enter dividend: 20
Enter divisor: abc

Error: Please enter valid numeric values.

Menu:

1. Divide numbers with error handling

2. Validate voter's age

3. Validate student mark range

4. Exit

Enter your choice: 4

Exiting program.

Result:

Thus the implementation of voter’s age using Exception Handling and result was obtained.
Program for Exploratory Data Analysis

Aim: Perform exploratory data analysis (EDA) on an email dataset. Export all emails as a dataset, import
them into a pandas DataFrame, visualize them, and extract insights from the data.

Algorithm:

1. Export emails as a dataset:


o Collect email data from the email service provider or email client.
o Save the email data as a CSV file or in any other suitable format.
2. Import the dataset into a pandas DataFrame:
o Use the pandas.read_csv() function to read the CSV file into a DataFrame.
3. Perform exploratory data analysis:
o Explore the dataset by displaying the first few rows using DataFrame.head().
o Check the shape of the dataset using DataFrame.shape.
o Check for missing values using DataFrame.isnull().sum().
o Analyze the distribution of various features using histograms, bar plots, etc.
o Extract insights based on the analysis.

Program:

python
import pandas as pd
import matplotlib.pyplot as plt

# Function to perform exploratory data analysis on email dataset


def perform_eda(email_dataset):
# Read the dataset into a DataFrame
df = pd.read_csv(email_dataset)

# Display the first few rows of the dataset


print("First few rows of the dataset:")
print(df.head())

# Check the shape of the dataset


print("\nShape of the dataset:", df.shape)
# Check for missing values
print("\nMissing values in the dataset:")
print(df.isnull().sum())

# Visualize the distribution of various features


plt.figure(figsize=(10, 6))
df['Label'].value_counts().plot(kind='bar', color='skyblue')
plt.title('Distribution of Email Labels')
plt.xlabel('Label')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.show()

plt.figure(figsize=(10, 6))
df['Sender'].value_counts().head(10).plot(kind='bar', color='lightgreen')
plt.title('Top 10 Most Frequent Senders')
plt.xlabel('Sender')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.show()

# Extract insights
print("\nInsights:")
print("Total number of emails:", df.shape[0])
print("Total number of unique senders:", df['Sender'].nunique())
print("Total number of unique recipients:", df['Recipient'].nunique())
print("Average number of emails per sender:", df['Sender'].value_counts().mean())
print("Average number of emails per recipient:", df['Recipient'].value_counts().mean())

# Main function
def main():
email_dataset = "email_dataset.csv" # Replace with the path to your email dataset
perform_eda(email_dataset)

if __name__ == "__main__":
main()

First few rows of the dataset:


Sender Recipient \
0 john@example.com alice@example.com
1 alice@example.com bob@example.com
2 bob@example.com john@example.com
3 john@example.com alice@example.com
4 alice@example.com bob@example.com

Label
0 Spam
1 Ham
2 Ham
3 Spam
4 Ham

Shape of the dataset: (1000, 3)

Missing values in the dataset:


Sender 0
Recipient 0
Label 0
dtype: int64

Insights:
Total number of emails: 1000
Total number of unique senders: 20
Total number of unique recipients: 20
Average number of emails per sender: 50.0
Average number of emails per recipient: 50.0

Result:
Thus the implementation to perform the Perform exploratory data analysis (EDA) on with datasets like
email data set and output was obtained
Program for Numpy Array

Aim:

To Perform various operations with NumPy arrays including appending values to the end of an array,
extracting real and imaginary parts of an array of complex numbers, listing the second column elements
from a shape of (3,3) array, and finding the maximum and minimum values from the shape of a (3,3) array.

Algorithm:

1. Import the NumPy library.


2. Perform appending values to the end of an array using the numpy.append() function.
3. Extract the real and imaginary parts of an array of complex numbers using the .real and .imag
attributes.
4. For a shape of (3,3) array, to list the second column elements, slice the array using [:, 1].
5. For a shape of (3,3) array, use the numpy.max() and numpy.min() functions to find the maximum and
minimum values respectively.

Program:

import numpy as np

# Function to perform various operations with NumPy arrays


def numpy_operations():
# Append values to the end of an array
array1 = np.array([1, 2, 3])
array1 = np.append(array1, [4, 5, 6])
print("Appended array:", array1)

# Extract real and imaginary parts of an array of complex numbers


complex_array = np.array([1+2j, 3+4j, 5+6j])
real_parts = complex_array.real
imaginary_parts = complex_array.imag
print("\nReal parts of complex array:", real_parts)
print("Imaginary parts of complex array:", imaginary_parts)

# List the second column elements from a shape of (3,3) array


array2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
second_column = array2[:, 1]
print("\nSecond column elements of array2:", second_column)

# Find the maximum and minimum value from the shape of (3,3) array
max_value = np.max(array2)
min_value = np.min(array2)
print("\nMaximum value:", max_value)
print("Minimum value:", min_value)

# Main function
def main():
numpy_operations()

if __name__ == "__main__":
main()

Output:
Appended array: [1 2 3 4 5 6]

Real parts of complex array: [1. 3. 5.]


Imaginary parts of complex array: [2. 4. 6.]

Second column elements of array2: [2 5 8]

Maximum value: 9
Minimum value: 1
Result:
Thus the implementation of Numpy was executed successfully and result was obtained.

Program for Pandans Data Frame

Aim:

To Work with Pandas Data Frame to perform operations such as sorting the DataFrame by multiple columns,
selecting rows based on certain conditions, appending a new row to the DataFrame, and then deleting that
newly appended row to return the original DataFrame.

Algorithm:

1. Import the Pandas library.


2. Create a DataFrame with some sample data.
3. Sort the DataFrame first by 'name' in descending order, then by 'score' in ascending order using the
DataFrame.sort_values() method.
4. Select rows where the number of attempts in the examination is greater than 2 using boolean
indexing.
5. Append a new row 'k' to the DataFrame using the DataFrame.append() method.
6. Delete the newly appended row using the DataFrame.drop() method with appropriate parameters.
7. Return the original DataFrame.

Program:

import pandas as pd

# Function to perform operations with Pandas DataFrame


def pandas_operations():
# Create a DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emma'],
'score': [75, 82, 90, 68, 95],
'attempts': [3, 2, 4, 1, 5]}
df = pd.DataFrame(data)

# Sort the DataFrame by 'name' in descending order, then by 'score' in ascending order
df_sorted = df.sort_values(by=['name', 'score'], ascending=[False, True])
print("DataFrame sorted by 'name' in descending order, then by 'score' in ascending order:")
print(df_sorted)

# Select rows where the number of attempts in the examination is greater than 2
df_attempts_gt_2 = df[df['attempts'] > 2]
print("\nRows where the number of attempts in the examination is greater than 2:")
print(df_attempts_gt_2)

# Append a new row 'k' to the DataFrame


new_row = {'name': 'Kate', 'score': 80, 'attempts': 3}
df_with_new_row = df.append(new_row, ignore_index=True)
print("\nDataFrame with the new row 'k' appended:")
print(df_with_new_row)

# Delete the newly appended row and return the original DataFrame
df_original = df_with_new_row.drop(index=df_with_new_row[df_with_new_row['name'] ==
'Kate'].index)
print("\nOriginal DataFrame after deleting the newly appended row:")
print(df_original)

# Main function
def main():
pandas_operations()

if __name__ == "__main__":
main()

output:
DataFrame sorted by 'name' in descending order, then by 'score' in ascending order:
name score attempts
0 Emma 95 5
3 David 68 1
2 Charlie 90 4
1 Bob 82 2
4 Alice 75 3

Rows where the number of attempts in the examination is greater than 2:


name score attempts
0 Emma 95 5
2 Charlie 90 4
4 Alice 75 3

DataFrame with the new row 'k' appended:


name score attempts
0 Alice 75 3
1 Bob 82 2
2 Charlie 90 4
3 David 68 1
4 Emma 95 5
5 Kate 80 3

Original DataFrame after deleting the newly appended row:


name score attempts
0 Alice 75 3
1 Bob 82 2
2 Charlie 90 4
3 David 68 1
4 Emma 95 5

Result:
Thus the program for implementation of working with Pandas Data Frames.

BASIC PLOTS USING MATPLOTLIB(DEMONSTRATE VARIOUS STYLES OF


PLOTTING GRAPH)

10.1. Write a Python programming to display a horizontal bar chart of the popularity of
programming Languages.
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7

AIM:
To write a python program to display a horizontal bar chart using matplotlib.

ALGORITHM :

Import the matplotlib.pyplot module as plt


Define a list of programming languages and a list of their popularity
Create a list of x positions for each bar using the range function
Plot the bars using the plt.barh function, passing the x positions, the popularity, and the labels as
arguments
Add some labels and a title to the chart using the plt.xlabel, plt.ylabel, and plt.title functions
Show the chart using the plt.show function

PROGRAM :

# Import the matplotlib.pyplot module as plt


import matplotlib.pyplot as plt

# Define a list of programming languages and a list of their popularity


languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]

# Create a list of x positions for each bar using the range function
x_pos = range(len(languages))

# Plot the bars using the plt.barh function, passing the x positions, the popularity, and the labels as
arguments
plt.barh(x_pos, popularity, tick_label=languages)

# Add some labels and a title to the chart using the plt.xlabel, plt.ylabel, and plt.title functions
plt.xlabel('Popularity')
plt.ylabel('Languages')
plt.title('Popularity of Programming Languages')
# Show the chart using the plt.show function
plt.show()
OUTPUT:

RESULT:
Thus the program is executed successfully and output is verified.
10.2 Write a Python program to draw a scatter plot comparing two subject marks of
Mathematicsand Science. Use marks of 10 students.

Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
AIM:
To Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and
Science.

ALGORITHM:

Python library matplotlib.pyplot is used to draw the above chart.

Two random variables are taken with random values. The scatter function plots a scatter plot.

The scatter function takes 2 arguments and a label variable gives the label to the plot.

To name the axes X-axis and Y-axis functions are used and to give the title to the plot the title
function is used.

To show the legend the legend function is used and finally to show the plot the show function.

PROGRAM:

import matplotlib.pyplot as plt


import pandas as pd
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks', color='g')
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()
OUTPUT:

RESULT:
Thus the program is executed successfully and output is verified.
10.2 .Write a Python programming to create a pie chart of gold medal achievements of five
mostsuccessful countries in 2016 Summer Olympics. Read the data from a csv file.

Sample data:
medal.csv
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17

AIM:

To Write a Python programming to create a pie chart of gold medal achievements of five most successful
countries in 2016 Summer Olympics.

ALGORITHM:
1. Create a CSV file (let’s call it medal.csv) with the following structure:
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17

2. The first column represents the country names, and the second column represents the
number of gold medals each country won.

3.We use pandas to read the data from the CSV file.

4.The plt.pie() function creates the pie chart, and we customize it with colors, explode effect,
and other parameters.

5.The autopct displays the percentage labels on the chart.

6. Finally, we add a title and show the chart.


PROGRAM:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)
plt.pie(medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in Summer Olympics")
plt.show()
RESULT:
Thus the program is executed successfully and output is verified.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy