Lab Manual PDS
Lab Manual PDS
COURSE OBJECTIVES:
To develop proficiency in the concepts of lists, tuples, sets, and dictionaries to effectively address
real-world challenges.
To master the concepts such as functions, strings, modules, file handling, and exception handling.
To expose the analysis of various datasets Pandas Data frame, utilizing NumPy arrays and Pandas
Data frames, visualizing the data.
To exhibit the analysis of various datasets using the Matplotlib package.
To make real time Projects with different Packages.
LIST OF EXPERIMENTS
TOTAL: 30 PERIODS
COURSE OUTCOMES :
CO1 : Address real time applications using the concepts of lists, tuples, sets, and dictionaries
CO2 : Manage functions, strings, modules, file handling and exception handling.
CO3 : Visualize the data interpretation by utilizing NumPy arrays and Pandas Dataframes.
CO4 : Plot the real time datasets with the use of Matplotlib.
PO PSO
CO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
1 3 2 2 2 2 - - - - - - 1 1 2 1
2 3 2 2 2 2 - - - - - - 1 1 2 1
3 3 1 3 3 - - - - 2 3 3 3 2 2 2
4 3 1 3 3 - - - - 2 3 3 3 2 2 2
5 3 2 2 1 1 - - - 3 2 3 1 3 1 3
Avg. 3 1.6 2.4 2.2 1 0 0 0 1.4 1.6 1.8 1.8 1.8 1.8 1.8
AD23221 - PYTHON FOR DATA SCIENCE LABORATORY
INDEX
[Link] [Link] NAME OF THE EXPERIMENT
1 1a Python Programming Basics – Data Types, Control Flow, Functions,
Strings, Lists, and Tuples
2 1b Experiment: List Operations and Built-in Methods in Python
3 1c Experiment: Tuple Operations and Built-in Methods in Python
4 2 Implementation of Library management using List
5 3 Implementation of construction material management using list
6 4a Set Operations and Built-in Methods in Python
7 4b Dictionary Operations and Built-in Methods in Python
8 5 Implementing real-time applications using Sets
9 6a Implementing programs using Functions Factorial
10 6b Implementing programs using Functions using largest number in a list
11 6c Implementing programs using Functions using area of shape
12 7 String Functions Using Python
13 8 Implementing Programs Using Written Modules in Python
14 9 Program for File using Python
15 10 Program for Exception Handling
16 11 Program for Exploratory Data Analysis
17 12 a Working with NumPy Arrays and Pandas DataFrames
18 12 b Program for Numpy Array
19 12 c Program for Pandans Data Frame
20 13 a Basic Plots Using Matplotlib (Demonstrate Various Styles Of
Plotting Graph)
21 13 b Write a Python program to draw a scatter plot comparing two subject
marks of Mathematicsand Science. Use marks of 10 students.
22 13 c 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.
23 14 Frequency Distributions, Averages, and Variability
24 15 Normal Curves, Correlation, and Scatter Plots
1a) Python Programming Basics – Data Types, Control Flow, Functions, Strings, Lists, and
Tuples
a) Write a Python program to demonstrate different data types, variable assignments, and
evaluate expressions.
b) Write a Python program to check whether a given number is positive, negative, or zero
using if-elif-else conditions.
c) Write a Python program to print the first N Fibonacci numbers using a loop.
d) Write a Python program to find the factorial of a number using recursion.
e) Write a Python program to count the number of vowels, consonants, and spaces in a given
string.
f) Write a Python program to perform list operations such as appending, removing, sorting,
and list comprehension.
g) Write a Python program to create a tuple, access its elements, and return multiple values as
a tuple.
Aim
Algorithm:
Step 1: Understanding Data Types & Expressions
1. Declare and initialize variables of different types (int, float, string, boolean).
2. Perform arithmetic and logical expressions using these variables.
3. Display the results along with their data types.
1. Define a function that accepts two numbers and returns their sum and product.
2. Call the function and store the result in a tuple.
3. Display the tuple values separately.
a) Write a Python program to demonstrate different data types, variable assignments, and
evaluate expressions.
Program:
# Performing expressions
sum_var = integer_var + float_var
product_var = integer_var * float_var
# Display results
print("Integer:", integer_var, "Type:", type(integer_var))
print("Float:", float_var, "Type:", type(float_var))
print("String:", string_var, "Type:", type(string_var))
print("Boolean:", bool_var, "Type:", type(bool_var))
print("Sum:", sum_var)
print("Product:", product_var)
Output:
b) Write a Python program to check whether a given number is positive, negative, or zero
using if-elif-else conditions.
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Sample Output:
Enter a number: -5
The number is negative.
c) Write a Python program to print the first N Fibonacci numbers using a loop.
Program:
Sample Output:
Program:
Enter a number: 5
Factorial of 5 is 120
e) Write a Python program to count the number of vowels, consonants, and spaces in a given
string.
Program:
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
print("Spaces:", space_count)
Sample Output:
f) Write a Python program to perform list operations such as appending, removing, sorting,
and list comprehension.
Program:
g) Write a Python program to create a tuple, access its elements, and return multiple values as
a tuple.
Program:
num1, num2 = 6, 4
result = calculate(num1, num2)
print("Sum:", result[0])
print("Product:", result[1])
Output:
Sum: 10
Product: 24
Result:
The Python program for Python Programming Basics – Data Types, Control Flow, Functions, S
trings, Lists, and Tuples is executed, and the output is verified.
1. b) Experiment: List Operations and Built-in Methods in Python
AIM:
To write a Python program that demonstrates all the operations on lists, including:
List creation and initialization
Basic operations: indexing, slicing, looping
Adding and removing elements
Sorting, reversing, copying, searching
Mathematical operations on lists
List comprehension
ALGORITHM:
# Slicing
print("Sliced List (2nd to 4th element):", numbers[1:4])
print("Every second element:", numbers[::2])
# Modifying Lists
numbers[2] = 100 # Updating element
[Link](6) # Adding element at end
[Link](2, 50) # Inserting at a position
[Link]([7, 8, 9]) # Extending the list
# Copying a List
copy_list = [Link]()
another_copy = numbers[:] # Using slicing
print("Copied List:", copy_list)
# Using enumerate
for index, value in enumerate(numbers):
print(f"Index {index} -> {value}")
print("Squares:", squares)
print("Even Numbers:", even_numbers)
print("Uppercase Fruits:", uppercase_fruits)
OUTPUT:
RESULT:
The Python program for List Operations was successfully executed, demonstrating:
List creation, indexing, slicing
Adding, updating, and removing elements
Sorting, reversing, searching, counting
Mathematical operations on lists Copying and iterating through lists
List comprehension techniques
1. c). Experiment: Tuple Operations and Built-in Methods in Python
AIM:
To write a Python program that demonstrates all the operations on tuples, including:
Tuple creation and initialization
Accessing elements using indexing and slicing
Tuple immutability demonstration
Tuple operations (concatenation, repetition, membership tests)
Tuple assignment and unpacking
Tuple as function arguments and return values
Built-in methods available for tuples
ALGORITHM:
print("Tuple1:", tuple1)
print("Tuple2:", tuple2)
print("Tuple3:", tuple3)
print("Single-element Tuple:", single_element_tuple)
# Tuple Operations
tuple4 = (6, 7, 8)
concatenated_tuple = tuple1 + tuple4 # Concatenation
repeated_tuple = tuple2 * 2 # Repetition
result = calculate_sums(tuple1)
print("Sum, Max, Min from Tuple1:", result)
Tuple1: (1, 2, 3, 4, 5)
Tuple2: ('apple', 'banana', 'cherry')
Tuple3: (10, 20, 30, 40)
Single-element Tuple: (42,)
First element of tuple1: 1
Last element of tuple1: 5
Sliced Tuple1 (2nd to 4th element): (2, 3, 4)
Error: Tuples are immutable! -> 'tuple' object does not support item assignment
Concatenated Tuple: (1, 2, 3, 4, 5, 6, 7, 8)
Repeated Tuple: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Is 'apple' in tuple2? True
Is 10 in tuple3? True
Tuple Assignment - a: 100 b: 200 c: 300
After Swapping - x: 10 y: 5
Sum, Max, Min from Tuple1: (15, 5, 1)
Count of 2 in sample_tuple: 3
Index of 4 in sample_tuple: 4
RESULT:
The Python program for Tuple Operations was successfully executed, demonstrating:
Tuple creation, indexing, slicing
Immutability of tuples
Tuple operations (concatenation, repetition, membership test)
Tuple unpacking and assignment
Tuples as function arguments and return values
Built-in tuple methods (count(), index())
2. 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.
3. Main Function:
Program
class Book:
class Library:
def init (self):
[Link] = []
def add_book(self, book):
[Link](book)
def display_books(self):
if not [Link]:
print("No books in the library.")
else:
print(book)
def main():
library = Library()
while True:
print("\nLibrary Management System")
print("1. Add Book")
if choice == '1':
else:
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Available: Yes
Book 2:
Available: Yes
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Book 2:
Title: Introduction to Data Science
Author: David
Available: Yes
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 4
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 5
Result:
The Python program for Library stock management is executed, and the output is verified.
3. 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 display_materials():
print("Materials List:")
for material in materials:
while True:
if choice == '1':
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Output:
1. Add Material
2. Update Material
3. Display Materials
4. Exit
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 3
Materials List:
2. Update Material
3. Display Materials
4. Exit
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 2
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Enter your choice (1-4): 3
Materials List:
1. Add Material
2. Update Material
3. Display Materials
4. Exit
Result:
The Python program for construction materials management is executed, and the output is verified.
4.a) Set Operations and Built-in Methods in Python
AIM:
To write a Python program that demonstrates all the operations on sets, including:
ALGORITHM:
print("Set1:", set1)
print("Set2:", set2)
print("Set3:", set3)
print("Empty Set:", empty_set)
# Set Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
union_set = A | B # Union
intersection_set = A & B # Intersection
difference_set = A - B # Difference (A - B)
symmetric_difference_set = A ^ B # Symmetric Difference
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference (A - B):", difference_set)
print("Symmetric Difference:", symmetric_difference_set)
# Membership Test
print("Is 'banana' in set2?", "banana" in set2)
print("Is 50 in set3?", 50 in set3)
print("\nElements in Set2:")
for fruit in set2:
print(fruit, end=" ")
# Set Comprehension
squared_numbers = {x**2 for x in range(1, 6)}
print("\nSquared Numbers Set (using set comprehension):", squared_numbers)
Set1: {1, 2, 3, 4, 5}
Set2: {'banana', 'apple', 'cherry'}
Set3: {40, 10, 20, 30}
Empty Set: set()
Set1 after modifications: {1, 2, 4, 5, 6}
Set2 after update: {'orange', 'banana', 'apple', 'grape', 'cherry'}
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (A - B): {1, 2}
Symmetric Difference: {1, 2, 5, 6}
Is 'banana' in set2? True
Is 50 in set3? False
Elements in Set1:
12456
Elements in Set2:
orange banana apple grape cherry
Squared Numbers Set (using set comprehension): {1, 4, 9, 16, 25}
Original Sample Set: {1, 2, 3, 4, 5}
After Clear: set()
RESULT:
The Python program for Set Operations was successfully executed, demonstrating:
Set creation and initialization
Adding, updating, and removing elements
Mathematical set operations (union, intersection, difference, symmetric difference)
Set comprehension for dynamic set creation
Membership testing and iteration
Built-in set methods (add(), remove(), update(), discard(), clear())
4 b) Dictionary Operations and Built-in Methods in Python
AIM:
To write a Python program that demonstrates all the operations on dictionaries, including:
Dictionary creation and initialization
Adding, updating, and removing elements
Dictionary traversal (iteration)
Key-value operations
Built-in dictionary methodsDictionary comprehension
Nested dictionaries
Using get(), items(), keys(), values() methods
ALGORITHM:
# 7. Dictionary comprehension
squared_numbers = {x: x**2 for x in range(1, 6)}
print("Squared Numbers Dictionary:", squared_numbers)
# 8. Nested Dictionary
students = {
"student1": {"name": "Bob", "age": 22, "course": "AI"},
"student2": {"name": "Charlie", "age": 23, "course": "ML"},
}
print("Nested Dictionary:", students)
# 9. Dictionary Methods
dict_methods = {"a": 1, "b": 2, "c": 3}
dict_copy = dict_methods.copy() # Creates a shallow copy
dict_methods.clear() # Clears all elements from dictionary
RESULT:
The Python program for Dictionary Operations was successfully executed, demonstrating:
Dictionary creation and initialization
Adding, updating, and removing key-value pairs
Accessing values using get()
Iterating over dictionary keys, values, and items
Using dictionary comprehension for dynamic dictionary creation
Working with nested dictionaries
Using dictionary methods (pop(), popitem(), clear(), copy(), etc.)
5. 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):
[Link] = set()
[Link] = set()
self.customer_preferences = {}
def add_model_to_catalog(self, model):
[Link](model)
print(f"Model '{model}' added to the catalog.")
def remove_model_from_catalog(self, model):
if model in [Link]:
[Link](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 [Link]:
print("-", model)
def add_vehicle_to_inventory(self, vehicle):
[Link](vehicle)
# 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:
- SUV
-3
- Hatchback
- Sedan
- Truck
Menu:
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
6a). 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 n, denoted as n!, is the product of all positive integers less than or equal to n.
Algorithm:
Program:
def factorial(n):
result = 1
def main():
try:
num = int(input("Enter a non-negative integer: "))
if num < 0:
main()
Result:
Thus,the Implementing programs using Functions Factorial and result was obtained
6 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:
Program:
def find_largest(numbers):
if not numbers:
return None
max_number = numbers[0]
max_number = num
return max_number
def main():
try:
main()
output
Result:
Thus the implementation of the programs using Functions using largest number in a list and result was
obtained
6 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 [Link] * radius**2
print("3. Triangle")
if choice == '1':
try:
try:
except ValueError:
print("Invalid input. Please enter numeric values for length and width.")
try:
else:
print("Invalid choice. Please enter 1, 2, or 3.")
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
7. 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]
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
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.
8. Implementing Programs Using Written Modules in Python
AIM:
To implement a Python program demonstrating about module ,use predefined (built-in) modules, to
create and use user-defined modules, to import and use modules in different ways and the role of
__name__ == "__main__" in modules
ALGORITHM:
1. Understand Modules – A module is a Python file containing functions, classes, or variables that
can be reused in other programs.
2. Use Predefined Modules – Import and use standard library modules like math, random,
datetime, and os.
3. Create a User-Defined Module – Define functions inside a separate Python file and import it into
another script.
4. Use Different Import Techniques – import module, from module import function, import
module as alias, from module import *.
5. Use __name__ == "__main__" – Demonstrate the role of the special __name__ variable.
# Using os module
print("Current Working Directory:", [Link]())
# [Link]
def greet(name):
return f"Hello, {name}! Welcome to Python Modules."
def add(a, b):
return a + b
# [Link]
import mymodule # Importing user-defined module
RESULT:
The Python program for implementing and using modules was successfully executed, covering:
Usage of built-in modules (math, random, datetime, os)
Creation and usage of a user-defined module ([Link])
Different import methods (import, from module import function, import module as alias, from module
import *)
Understanding the role of __name__ == "__main__"
9. 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:
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: [Link]
Enter destination file name: [Link]
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: [Link]
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: [Link]
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
10. 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.")
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")
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.
11. 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:
Program:
python
import pandas as pd
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([Link]())
# Check the shape of the dataset
print([Link]().sum())
[Link]('Label')
[Link]('Count')
[Link](rotation=45)
[Link]()
[Link](figsize=(10, 6))
df['Sender'].value_counts().head(10).plot(kind='bar', color='lightgreen')
[Link](rotation=45)
[Link]()
# Extract insights
print("\nInsights:")
# Main function
def main():
main()
1 alice@[Link] bob@[Link]
2 bob@[Link] john@[Link]
3 john@[Link] alice@[Link]
4 alice@[Link] bob@[Link]
Label
0 Spam
1 Ham
2 Ham
3 Spam
4 Ham
Sender 0
Recipient 0
Label 0
dtype: int64
Insights:
Result:
Thus the implementation to perform the Perform exploratory data analysis (EDA) on with datasets like
email data set and output was obtained
12a). Working with NumPy Arrays and Pandas DataFrames
AIM:
To understand and implement various operations on:
NumPy Arrays – Creation, indexing, slicing, reshaping, mathematical operations, aggregation,
broadcasting, and advanced operations.
Pandas DataFrames – Creation, data selection, filtering, modifying, handling missing values, and
statistical analysis.
ALGORITHM:
A. NumPy Arrays:
1. Import NumPy and create arrays using array(), zeros(), ones(), arange(), linspace(), and random.
2. Perform Array Operations – Indexing, slicing, reshaping, concatenation, and mathematical
operations.
3. Aggregation & Broadcasting – Use functions like sum(), mean(), max(), and min().
B. Pandas DataFrames:
1. Import Pandas and create DataFrames using dictionaries, lists, and CSV/Excel files.
2. Perform Data Operations – Selecting columns, filtering rows, modifying values, and handling
missing data.
3. Analyze Data – Use statistical functions like describe(), groupby(), and visualization methods.
# Aggregation functions
arr6 = [Link](1, 100, (3, 3)) # Random 3x3 matrix
print("Sum:", [Link](arr6))
print("Mean:", [Link](arr6))
print("Max:", [Link](arr6))
print("Min:", [Link](arr6))
# Filtering rows
filtered_df = df[df['Age'] > 30] # Get employees older than 30
Sum: 450
Mean: 50.0
Max: 98
Min: 15
vbnet
CopyEdit
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
3 David 40 80000
Group by Age:
Age
30 60000
35 70000
40 80000
RESULT:
The Python program for working with NumPy Arrays and Pandas DataFrames was successfully
executed, covering:
NumPy array creation, indexing, slicing, reshaping, mathematical operations, aggregation, and
broadcasting.
Pandas DataFrame creation, data selection, filtering, modifying, handling missing values, and statistical
analysis.
12b). 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:
Program:
import numpy as np
def numpy_operations():
# Append values to the end of an array
real_parts = complex_array.real
imaginary_parts = complex_array.imag
print("\nReal parts of complex array:", real_parts)
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 = [Link](array2)
min_value = [Link](array2)
# Main function
def main():
numpy_operations()
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.
12c) 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:
Program:
import pandas as pd
# Create a DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emma'], 'score': [75, 82, 90, 68, 95], 'attempts': [3, 2, 4, 1,
5]}
df = [Link](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
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)
# Main function
def main():
pandas_operations()
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
2 Charlie 90 4
3 David 68 1
4 Emma 95 5
Result:
Thus the program for implementation of working with Pandas Data Frames.
13a). BASIC PLOTS USING MATPLOTLIB (DEMONSTRATE VARIOUS STYLES OF
PLOTTING GRAPH)
Aim
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 :
PROGRAM :
# Create a list of x positions for each bar using the range function
x_pos = range(len(languages))
# Plot the bars using the [Link] function, passing the x positions, the popularity, and the labels as
arguments
[Link](x_pos, popularity, tick_label=languages)
# Add some labels and a title to the chart using the [Link], [Link], and [Link] functions
[Link]('Popularity')
[Link]('Languages')
[Link]('Popularity of Programming Languages')
# Show the chart using the [Link] function
[Link]()
OUTPUT:
RESULT:
Thus the program is executed successfully and output is verified.
13b) 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:
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:
RESULT:
Thus the program is executed successfully and output is verified.
13 c) 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:
[Link]
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:
Create a CSV file (let’s call it [Link]) with the following structure:
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17
The first column represents the country names, and the second column represents the number
of gold medals each country won.
We use pandas to read the data from the CSV file.
The [Link]() function creates the pie chart, and we customize it with colors, explode effect, and
other parameters.
The autopct displays the percentage labels on the chart.
Finally, we add a title and show the chart.
PROGRAM:
import [Link] as plt
import pandas as pd
df = pd.read_csv('[Link]')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)
[Link](medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
[Link]("Gold medal achievements of five most successful\n"+"countries in Summer Olympics")
[Link]()
RESULT:
Thus the program is executed successfully and output is verified.
14. Frequency Distributions, Averages, and Variability
AIM:
ALGORITHM:
A. Frequency Distribution
PROGRAM:
import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from scipy import stats
[Link](1,2,2)
freq_dist.plot(kind='bar', color='salmon')
[Link]("Bar Chart of Frequency Distribution")
[Link]()
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Mode: {mode_value}")
print(f"Range: {range_value}")
print(f"Variance: {variance_value}")
print(f"Standard Deviation: {std_dev}")
print(f"Interquartile Range (IQR): {IQR}")
Frequency Distribution:
85 4
90 2
78 2
75 2
66 1
80 1
88 1
92 1
95 1
Name: Scores, dtype: int64
Mean: 83.13
Median: 85.0
Mode: 85
Range: 29
Variance: 56.04
Standard Deviation: 7.48
Interquartile Range (IQR): 10.0
Graphical Outputs
RESULT:
AIM:
ALGORITHM:
B. Correlation Analysis
C. Scatter Plot
PROGRAM:
import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from [Link] import norm
# Compute correlation
correlation_matrix = [Link]()
print("Correlation Matrix:\n", correlation_matrix)
# Heatmap of correlation
[Link](figsize=(6, 4))
[Link](correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
[Link]("Correlation Heatmap")
[Link]()
# Regression Line
[Link](x=df['Age'], y=df['Salary'], scatter=False, color='red')
[Link]()
OUTPUT:
Correlation Matrix:
Age Salary
Age 1.00 -0.02
Salary -0.02 1.00
3. Scatter plot with regression line: Shows the relationship between Age
and Salary.
RESULT:
The Python program for Normal Curves, Correlation, and Scatter Plots was
successfully executed. It covered:
Normal distribution visualization using [Link]().
Correlation analysis using .corr() and heatmap().
Scatter plot with regression line using scatterplot() and regplot().