Ad23221 Python for Data Science Record
Ad23221 Python for Data Science Record
NAME .............................................................................................................
SUBJECT ..........................................................................................................
BRANCH ...........................................................................................................
ROLL No ........................................................................................
SEMESTER ..........................................................................................................
BONAFIDE CERTIFICATE
Signature Signature
Faculty - in - Charge H.O.D
Aim
To understand and implement fundamental Python concepts, including:
Algorithm:
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.
Step 2: Implementing Conditional Statements
2
Step 3: Using Iterative Statement
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.
3
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:
4
b) Write a Python program to check whether a given number is positive, negative,
or zero using if-elif-else conditions.
elif-else) Program:
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:
Output:
Scope) Program:
Output:
6
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)
Output:
7
f) Write a Python program to perform list operations such as appending, removing,
sorting, and list comprehension.
Output:
8
g) Write a Python program to create a tuple, access its elements, and return multiple
values as a tuple.
num1, num2 = 6, 4
result = calculate(num1, num2)
Output:
Sum:10
Product:24
9
Result:
The Python program for Python Programming Basics – Data Types, Control Flow,
Functions,
Strings, Lists, and Tuples is executed, and the output is verified.
10
EX. NO. 1b) Experiment: List Operations and Built-in Methods in
DATE: 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:
11
PROGRAM: List Operations in Python
# Slicing
print("Sliced List (2nd to 4th element):", numbers[1:4])
print("Every second element:", numbers[::2])
# Modifying Lists
numbers[2] = 100 # Updating element
numbers.append(6) # Adding element at end
numbers.insert(2, 50) # Inserting at a position
numbers.extend([7, 8, 9]) # Extending the list
# Copying a List
copy_list = numbers.copy()
another_copy = numbers[:] # Using slicing
print("Copied List:", copy_list)
# Iterating through a
List for num in
numbers:
print(num, end="
") print()
# Using enumerate
for index, value in enumerate(numbers):
print(f"Index {index} -> {value}")
13
OUTPUT:
14
RESULT:
AIM:
To write a Python program that demonstrates all the operations on tuples, including:
Tuple creation and initialization
ALGORITHM:
16
PROGRAM: Tuple Operations in Python
# Demonstrating Tuple
Immutability try:
tuple1[1] = 100 # This will raise an
error except TypeError as e:
print("Error: Tuples are immutable! ->", e)
# Tuple
Operations
tuple4 = (6,
7, 8)
concatenated_tuple = tuple1 + tuple4 # Concatenation
repeated_tuple = tuple2 * 2 # Repetition
print("Concatenated Tuple:",
concatenated_tuple) print("Repeated Tuple:",
repeated_tuple)
# Membership test
print("Is 'apple' in tuple2?", "apple" in tuple2)
print("Is 10 in tuple3?", 10 in tuple3)
17
# Swapping values using tuple
unpacking x, y = 5, 10
x, y = y, x # Swapping using tuple unpacking
print("After Swapping - x:", x, "y:", y)
result = calculate_sums(tuple1)
print("Sum, Max, Min from Tuple1:", result)
18
OUTPUT:
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
19
RESULT:
20
EX. NO. 2 Implementation of Library management using List
DATE:
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:
3. Main Function:
21
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(book)
def
borrow_boo
k(self, title):
for book in
self.books:
22
print(f"{book.title} borrowed successfully.")
return
def
return_book(self,
self.books:
print(f"{book.title} returned
successfully.") return
def main():
library =
Library()
while True:
print(“2.Display Book”)
print(“3.Borrow
Book”)
print("5. Exit")
if choice == '1':
author)
library.add_book(book)
library.display_books()
elif choice
== '5':
print("Exi
ting the
program."
) break
else:
if__name__==”__main__”:
main()
24
Output:
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Title: Think
Python
Author:
Allen
Available:
Yes Book 2:
Available: Yes
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
25
Enter your choice: 3
successfully.
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Title:
Think
Python
Author:
Allen Available:
No Book 2:
Available: Yes
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
26
Enter your choice: 3
available.
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
successfully.
1. Add Book
2. Display Books
3. Borrow Book
4. Return Book
5. Exit
Enter your
choice: 5
Exiting the
program.
27
Result:
The Python program for Library stock management is executed, and the output is verified.
28
EX. NO. 3 Implementation of construction material
management using list
DATE:
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:
29
Program:
# Initialize an empty list to store construction
materials materials = []
materials.append(material)
quantity,
for i, material in
enumerate(materials):
if material[0]
== name:
price_per_unit) print(f"{name}
def display_materials():
print("No materials
found.") else:
30
print("Material
s List:") for
material in
materials:
program
loop
while
True:
print("\nConstruction Materials
Material")
print("2. Update
Material") print("3.
Display Materials")
print("4. Exit")
if choice == '1':
31
price_per_unit = float(input("Enter new
price per unit: "))
update_material(name, quantity,
price_per_unit)
display_materials()
print("Exiting
program.") break
else:
32
Output:
1. Add Material
2. Update Material
3. Display Materials
4. Exit
(1-4): 1 Enter
material name:
cement Enter
quantity: 10 Enter
1. Add Material
2. Update Material
3. Display Materials
4. Exit
(1-4): 3 Materials
List:
1. Add Material
2. Update Material
3. Display Materials
4. Exit
(1-4): 1 Enter
33
material name:
steel Enter
quantity: 100
2. Update Material
3. Display Materials
4. Exit
list.
1. Add Material
2. Update Material
3. Display Materials
4. Exit
(1-4): 3 Materials
List:
34
Construction Materials Management System
1. Add Material
2. Update Material
3. Display Materials
4. Exit
(1-4): 4 Exiting
program.
Result:
The Python program for construction materials management is executed, and the output is
verified.
35
EX. NO. 4a) Set Operations and Built-in Methods in Python
DATE:
AIM:
To write a Python program that demonstrates all the operations on sets, including:
ALGORITHM:
36
PROGRAM: Set Operations in Python
print("Set1:", set1)
print("Set2:", set2)
print("Set3:", set3)
print("Empty Set:",
empty_set)
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)
38
OUTPUT:
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()
39
RESULT:
40
EX. NO. 4b) Dictionary Operations and Built-in Methods in Python
DATE:
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:
41
PROGRAM: Dictionary Operations in Python
# 7. Dictionary comprehension
squared_numbers = {x: x**2 for x in range(1, 6)}
print("Squared Numbers Dictionary:", squared_numbers)
42
# 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
43
OUTPUT:
44
RESULT:
45
EX. NO. 5 Implementing real-time applications using Sets
DATE:
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.
46
Program:
class
Automobile: def
init (self):
self.catalog = set()
self.inventory = set()
self.customer_preferen
ces = {}
if model in self.catalog:
self.catalog.remove(model)
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(veh
icle) print(f"Vehicle
'{vehicle}' sold.")
else:
47
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.")
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())
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")
48
auto.add_model_to_catalog("Truck")
auto.add_vehicle_to_inventory("SUV-001)
auto.add_vehicle_to_inventory("Sedan-00 1")
auto.add_vehicle_to_inventory("Hatchbac k-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")
auto.display_inve
ntory() elif choice
== '3':
elif choice
== '4':
print("Exi
ting the
program."
) break
else:
print("Invalid choice. Please enter a number from 1 to 4.")
50
Output:
Menu:
2. Inventory Management
4. Exit
- SUV
-3
- Hatchback
- Sedan
- Truck
Menu:
2. Inventory Management
4. Exit
51
Result:
Thus, the implementation of Vehicle implementation are implemented and result was
obtained
52
EX. NO. 6a) Implementing programs using Functions
Factorial
DATE:
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:
1. Define a function named factorial that takes an integer parameter n. Initialize a variable
result to 1. This variable will store the factorial value. Use a loop to iterate from 1 to n
(inclusive).
2. Multiply result by the current value of the loop variable. After the loop, return the value of
result as the factorial of n. 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.
53
Program:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i # Multiply 'result' by 'i'
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()
54
Output :
Enter a non-negative integer: 5
The factorial of 5 is 120.
Result:
Thus, the Implementing programs using Functions Factorial and result was obtained.
55
EX. NO.6(b) Implementing programs using Functions using largest
number in a list
DATE:
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:
2. Initialize a variable largest to store the largest number found in the list. Set it
initially to the first element of the list.
4. After iterating through the entire list, return the value of largest.
56
Program:
def find_largest(numbers):
if not numbers:
return None
max_number = numbers[0]
max_number = num
return max_number
def main():
try:
largest = find_largest(numbers)
else:
except ValueError:
if __name__ == "__main__":
main()
57
output:
Result:
Thus the implementation of the programs using Functions using largest number in a list and
result was obtained
58
EX. NO. 6c) Implementing programs using Functions using area of shape
DATE:
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:
59
Program:
import math
def circle_area(radius):
return math.pi * radius**2
def main():
print("Calculate Area of Shapes:")
print("1. Circle")
print("2. Rectangle")
print("3. Triangle")
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.")
60
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()
61
Output:
Calculate Area of Shapes:
1. Circle
2. Rectangle
3. Triangle
Enter your choice (1/2/3): 1
Enter the radius of the circle: 5
The area of the circle is 78.53981633974483.
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.
62
EX. NO. 7 String Functions using python
DATE:
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.
63
Program:
# Function to reverse a string
def reverse_string(string):
return string[::-1]
def is_palindrome(string):
def count_characters(string):
char_count = {}
char_count[char] = char_count.get(char, 0) + 1
return char_count
def main():
while True:
print("\nMenu:")
print("5. Exit")
if choice == '1':
else:
char_count = count_characters(string)
print("Character count:")
print("Exiting program.")
break
else:
if __name__ == "__main__":
main()
65
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
66
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.
67
Result:
Thus the Implementing programs using Strings. (reverse, palindrome, character count,
replacing characters) and result was obtained.
68
EX. NO. 8 Implementing Programs Using Written Modules in Python
DATE:
AIM:
ALGORITHM:
69
PROGRAM: Implementing and Using Modules in
# Using os module
print("Current Working Directory:", os.getcwd())
70
Step 2: Creating a User-Defined Module
# mymodule.py
def greet(name):
return a + b
if __name__ == "__main__":
else:
71
Step 3: Importing and Using the User-Defined Module
# main.py
import mymodule # Importing user-defined module
72
OUTPUT:
Modules.
Addition of 5 and 3: 8
Modules.
30
Modules.
directly
73
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 (mymodule.py)
Different import methods (import, from module import function, import module as alias, from
module import *)
Understanding the role of name == " main "
74
EX. NO. 9 Program for File using Python
DATE:
Aim:
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.
75
Program:
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")
if choice == '1':
source_file = input("Enter source file name: ")
destination_file = input("Enter destination file name: ")
76
try:
copy_file(source_file, destination_file)
except FileNotFoundError:
print("Source file not found.")
elif choice == '2':
file_name = input("Enter file name: ")
try:
print("Number of words in the file:", count_words(file_name))
except FileNotFoundError:
print("File not found.")
elif choice == '3':
file_name = input("Enter file name: ")
try:
print("Longest word in the file:", longest_word(file_name))
except FileNotFoundError:
print("File not found.")
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
77
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:
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.
78
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 to
another, word count, longest word) result was obtained
79
EX. NO. 10 Program for Exception Handling
DATE:
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.
80
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.")
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")
81
if choice == '1':
try:
dividend = float(input("Enter dividend: "))
divisor = float(input("Enter divisor: "))
print("Result:", divide(dividend, divisor))
except ZeroDivisionError as zde:
print(zde)
except ValueError:
print("Error: Please enter valid numeric values.")
else:
print("Invalid choice. Please try again.")
82
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.
83
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.
84
Result:
Thus, the Implementing real-time/technical applications using Exception handling is
successfully executed.
85
EX. NO. 11 Program for Exploratory Data Analysis
DATE:
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:
86
Program:
import pandas as pd
import matplotlib.pyplot as plt
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.show()
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.show()
87
# Extract insights
print("\nInsights:")
def main():
# Entry point
if __name__ == "__main__":
main()
88
OUTPUT:
0 [email protected] [email protected]
1 [email protected] [email protected]
2 [email protected] [email protected]
3 [email protected] [email protected]
Label
0 Spam
1 Ham
2 Ham
3 Spam
4 Ham
Sender 0
Recipient 0
Insights:
unique senders: 20
sender: 50.0
89
Result:
Thus the implementation to perform the Perform exploratory data analysis (EDA) on with
datasets like email data set and output was obtained
90
EX. NO. 12a) Working with NumPy Arrays and Pandas DataFrames
DATE:
AIM:
To understand and implement various operations on:
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.
91
PROGRAM: Working with NumPy Arrays and Pandas
import numpy as np
sum_arr = arr1 + 5
mult_arr = arr1 * 2
# Aggregation functions
print("Sum:", np.sum(arr6))
print("Mean:", np.mean(arr6))
print("Max:", np.max(arr6))
print("Min:", np.min(arr6))
arr7 = arr6.reshape(1, 9)
import pandas as pd
data = {
df = pd.DataFrame(data)
# Filtering rows
df.fillna(df.mean(numeric_only=True), inplace=True)
93
# Grouping and aggregation
grouped = df.groupby('Age')['Salary'].mean()
df.to_csv("employee_data.csv", index=False)
df_read = pd.read_csv("employee_data.csv")
94
OUTPUT:
Random Array (arr6):
[[59 91 72]
[98 50 57]
[ 4 9 73]]
Sum: 513
Mean: 57.0
Max: 98
Min: 4
DataFrame Head:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
3 David 40 80000
Statistical Summary:
Age Salary
count 4.000000 4.000000
mean 32.500000 65000.000000
std 6.454972 12909.944487
min 25.000000 50000.000000
25% 28.750000 57500.000000
50% 32.500000 65000.000000
75% 36.250000 72500.000000
max 40.000000 80000.000000
Selected Columns:
Name Salary
0 Alice 50000
1 Bob 60000
2 Charlie 70000
3 David 80000
95
Grouped by Age (Salary Mean):
Age
25.0 50000.0
30.0 60000.0
32.5 90000.0
35.0 70000.0
40.0 80000.0
Name: Salary, dtype: float64
96
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.
97
EX. NO. 12b) Program for Numpy Array
DATE:
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:
98
Program:
import numpy as np
def numpy_operations():
real_parts = complex_array.real
imaginary_parts = complex_array.imag
second_column = array2[:, 1]
# Find the maximum and minimum value from the shape of (3,3) array
max_value = np.max(array2)
min_value = np.min(array2)
# Main function
def main():
numpy_operations()
if __name__ == "__main__":
main()
99
Output:
Appended array: [1 2 3 4 5 6]
Maximum value: 9
Minimum value: 1
Result:
Thus the implementation of Numpy was executed successfully and result was obtained.
100
EX. NO. 12c) Program for Pandas Data Frame
DATE:
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:
101
Program:
import pandas as pd
# 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)
# Delete the newly appended row and return the original DataFrame
df_original = df_with_new_row[df_with_new_row['name'] != 'Kate']
print("\nOriginal DataFrame after deleting the newly appended row:")
print(df_original)
# Main function
def main():
pandas_operations()
if __name__ == "__main__":
main()
102
output:
103
Result:
Thus the program for implementation of working with Pandas Data Frames.
104
EX. NO. 13a) Basic Plots Using Matplotlib (Demonstrate Various Styles Of
Plotting Graph)
DATE:
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
ALGORITHM :
105
PROGRAM :
# Create a list of x positions for each bar using the range function
x_pos = range(len(languages))
106
OUTPUT:
RESULT:
107
EX. NO. 13b) Write a Python program to draw a scatter plot comparing two
subject marks of Mathematics and Science. Use marks of 10
DATE: 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
▪ 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.
108
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()
109
OUTPUT:
RESULT:
Thus the program is executed successfully and output is verified.
110
EX. NO. 13c) Write a Python programming to create a pie chart of gold
medal achievements of five most successful countries in
DATE: 2016 Summer Olympics. Read the data from a csv file.
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 medal.csv) 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 plt.pie() 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.
111
PROGRAM:
import matplotlib.pyplot as plt
import pandas as pd
# Adding a title
plt.title("Gold Medal Achievements of Five Most Successful\nCountries in the 2016 Summer
Olympics")
112
OUTPUT:
RESULT:
Thus the program is executed successfully and output is verified.
113
EX. NO. 14 Frequency Distributions, Averages, and Variability
DATE:
AIM:
ALGORITHM:
A. Frequency Distribution
114
PROGRAM:
import numpy
as np import
pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
plt.subplot(1,2,2)
freq_dist.plot(kind='bar', color='salmon')
plt.title("Bar Chart of Frequency Distribution")
plt.show()
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Mode: {mode_value}")
115
df['Scores'].min() variance_value =
df['Scores'].var()
std_dev = df['Scores'].std()
Q1 =
df['Scores'].quantile(0.25)
Q3 =
df['Scores'].quantile(0.75)
IQR = Q3 - Q1
print(f"Range: {range_value}")
print(f"Variance: {variance_value}")
print(f"Standard Deviation: {std_dev}")
print(f"Interquartile Range (IQR): {IQR}")
116
OUTPUT:
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
117
RESULT:
118
EX. NO. 15 Normal Curves, Correlation, and Scatter Plots
DATE:
AIM:
ALGORITHM:
B. Correlation Analysis
C. Scatter Plot
119
PROGRAM:
import numpy
as np import
pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
# Plot histogram of
data
plt.figure(figsize=(
10, 5))
sns.histplot(data, bins=30, kde=True, color='skyblue')
plt.title("Normal Distribution
Curve") plt.xlabel("Values")
plt.ylabel("Frequency")
plt.grid()
plt.show()
# **B. Correlation
Analysis** # Creating
a sample dataset
np.random.seed(42)
data = {'Age': np.random.randint(20, 60, 100),
'Salary': np.random.randint(30000, 100000,
100)} df = pd.DataFrame(data)
# Compute correlation
correlation_matrix = df.corr()
print("Correlation Matrix:\n", correlation_matrix)
# Heatmap of correlation
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
plt.title("Correlation Heatmap")
plt.show()
# Regression Line
sns.regplot(x=df['Age'], y=df['Salary'], scatter=False,
color='red') plt.show()
121
OUTPUT:
122
Correlation Analysis Output
Correlation
Matrix:
Age
Salary
Age 1.00 -0.02
Salary -0.02 1.00
123
RESULT:
The Python program for Normal Curves, Correlation, and Scatter Plots
was successfully executed. It covered:
Normal distribution visualization using numpy.random.normal().
Correlation analysis using .corr() and heatmap().
Scatter plot with regression line using scatterplot() and regplot().
124