0% found this document useful (0 votes)
17 views81 pages

Lab Manual PDS

The document outlines the objectives and experiments for a Python for Data Science laboratory course, focusing on data structures, functions, data analysis, and visualization techniques. Students will gain hands-on experience through various experiments involving lists, tuples, sets, dictionaries, and libraries like NumPy and Matplotlib. The course aims to equip students with practical skills to address real-world data challenges and complete projects using Python.

Uploaded by

jaivantr01
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)
17 views81 pages

Lab Manual PDS

The document outlines the objectives and experiments for a Python for Data Science laboratory course, focusing on data structures, functions, data analysis, and visualization techniques. Students will gain hands-on experience through various experiments involving lists, tuples, sets, dictionaries, and libraries like NumPy and Matplotlib. The course aims to equip students with practical skills to address real-world data challenges and complete projects using Python.

Uploaded by

jaivantr01
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

AD23221 PYTHON FOR DATA SCIENCE LABORATORY LTPC 0021

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

1. Implementing real-time/technical applications using Lists, Tuples.


2. Implementing real-time/technical applications using Sets, Dictionaries
3. Implementing programs using Functions.
4. Implementing programs using Strings.
5. Implementing programs using written modules.
6. Implementing real-time/technical applications using File handling.
7. Implementing real-time/technical applications using Exception handling.
8. Perform exploratory data analysis (EDA) on with datasets like email data set. Export all your
emails as a dataset, import them inside a pandas data frame, visualize them and get different
insights from the data.
9. Working with Numpy arrays and Pandas data frames
10. Basic plots using Matplotlib
11. Frequency distributions, Averages, Variability
12. Normal curves, Correlation and scatter plots, Correlation coefficient

TOTAL: 30 PERIODS
COURSE OUTCOMES :

At the end of the course the students will be able to

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.

CO5 : Construct real-time projects utilizing various packages


COs-POs & PSOs MAPPING

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

To understand and implement fundamental Python concepts, including:

 Data types, variables, and expressions.


 Conditional statements (if-elif-else).
 Iterations (for, while, break, continue).
 Functions (recursion, return, scope).
 String operations (counting vowels, consonants, spaces).
 Lists (operations, methods, list comprehension).
 Tuples (assignment, returning multiple values).

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.

Step 2: Implementing Conditional Statements

1. Accept a number from the user.


2. Use if-elif-else statements to check whether the number is positive, negative, or zero.
3. Display the appropriate message.

Step 3: Using Iterative Statements

1. Accept an integer N from the user.


2. Use a while loop to print the first N Fibonacci numbers.
3. Display the sequence.

Step 4: Defining and Calling Functions

1. Define a recursive function to calculate the factorial of a number.


2. Accept an integer input from the user.
3. Call the function and display the factorial.
Step 5: Performing String Operations

1. Accept a string from the user.


2. Count and display the number of vowels, consonants, and spaces in the string.

Step 6: Performing List Operations

1. Create a list with five random numbers.


2. Perform operations: append, remove, and sort.
3. Use list comprehension to generate a new list with squared values.

Step 7: Using Tuples for Data Handling

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:

# Demonstrating data types, variables, and expressions


integer_var = 10 # Integer
float_var = 5.5 # Float
string_var = "Python" # String
bool_var = True # Boolean

# 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:

Integer: 10 Type: <class 'int'>


Float: 5.5 Type: <class 'float'>
String: Python Type: <class 'str'>
Boolean: True Type: <class 'bool'>
Sum: 15.5
Product: 55.0

b) Write a Python program to check whether a given number is positive, negative, or zero
using if-elif-else conditions.

Conditional Statements (if-elif-else)


Program:

# Check if a number is positive, negative, or zero


num = int(input("Enter a number: "))

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.

Loops (Iteration: while, for, break, continue, pass)

Program:

# Print the first N Fibonacci numbers


n = int(input("Enter the number of terms: "))
a, b = 0, 1
count = 0

while count < n:


print(a, end=" ")
a, b = b, a + b
count += 1

Sample Output:

Enter the number of terms: 7


0 1 1 2 3 5 8

d) Write a Python program to find the factorial of a number using recursion.

Functions (Recursion, Return, Local & Global Scope)

Program:

# Find the factorial of a number using recursion


def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = int(input("Enter a number: "))


print("Factorial of", num, "is", factorial(num))
Sample Output:

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.

String Operations (Counting Vowels, Consonants, Spaces)

Program:

# Count vowels, consonants, and spaces in a string


string = input("Enter a string: ")
vowels = "aeiouAEIOU"
vowel_count = consonant_count = space_count = 0

for char in string:


if char in vowels:
vowel_count += 1
elif [Link]():
consonant_count += 1
elif [Link]():
space_count += 1

print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
print("Spaces:", space_count)

Sample Output:

Enter a string: Hello World


Vowels: 3
Consonants: 7
Spaces: 1

f) Write a Python program to perform list operations such as appending, removing, sorting,
and list comprehension.

Lists (Operations, Methods, List Comprehension)

Program:

# List operations: append, remove, sort, list comprehension


numbers = [5, 2, 9, 1, 7]
[Link](10)
[Link](2)
[Link]()

# List comprehension to create a squared list


squared_numbers = [x ** 2 for x in numbers]

print("Modified List:", numbers)


print("Squared List:", squared_numbers)
Output:

Modified List: [1, 5, 7, 9, 10]


Squared List: [1, 25, 49, 81, 100]

g) Write a Python program to create a tuple, access its elements, and return multiple values as
a tuple.

Tuples (Assignment, Return Multiple Values)

Program:

# Tuple assignment and returning multiple values


def calculate(a, b):
sum_val = a + b
product = a * b
return sum_val, product # Returning tuple

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:

1. Create a list using different methods.


2. Access elements using indexing and slicing.
3. Modify elements (update, append, insert, extend).
4. Remove elements using pop(), remove(), del, clear().
5. Search and count elements using index() and count().
6. Sort and reverse lists using sort() and reverse().
7. Use list comprehension for concise operations.
8. Copy lists correctly using copy() and slicing.
9. Perform mathematical operations using sum(), min(), max().
10. Iterate through the list using loops and enumerate().

PROGRAM: List Operations in Python

# List creation using different methods


numbers = [1, 2, 3, 4, 5]
fruits = list(("apple", "banana", "cherry"))
mixed_list = [10, "Hello", 3.14, True]

print("Numbers List:", numbers)


print("Fruits List:", fruits)
print("Mixed List:", mixed_list)

# Accessing list elements


print("First element:", numbers[0])
print("Last element:", numbers[-1])

# 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

print("Updated Numbers List:", numbers)


# Removing Elements
[Link]() # Removes last element
[Link](50) # Removes first occurrence of 50
del numbers[1] # Deletes element at index 1
[Link]() # Clears the list

print("Numbers List after Deletion:", numbers)

# Recreating numbers list


numbers = [5, 2, 8, 3, 1]

# Sorting and Reversing


[Link]() # Sorts in ascending order
print("Sorted List:", numbers)

[Link](reverse=True) # Descending order


print("Descending Order List:", numbers)

[Link]() # Reverses the list


print("Reversed List:", numbers)

# Searching and Counting Elements


[Link](2)
print("Index of 2:", [Link](2))
print("Count of 2:", [Link](2))

# Mathematical operations on lists


print("Sum of numbers:", sum(numbers))
print("Min value:", min(numbers))
print("Max value:", max(numbers))

# Copying a List
copy_list = [Link]()
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}")

# List Comprehension Examples


squares = [x**2 for x in range(1, 6)]
even_numbers = [x for x in range(10) if x % 2 == 0]
uppercase_fruits = [[Link]() for fruit in fruits]

print("Squares:", squares)
print("Even Numbers:", even_numbers)
print("Uppercase Fruits:", uppercase_fruits)
OUTPUT:

Numbers List: [1, 2, 3, 4, 5]


Fruits List: ['apple', 'banana', 'cherry']
Mixed List: [10, 'Hello', 3.14, True]
First element: 1
Last element: 5
Sliced List (2nd to 4th element): [2, 3, 4]
Every second element: [1, 3, 5]
Updated Numbers List: [1, 2, 50, 100, 4, 5, 6, 7, 8, 9]
Numbers List after Deletion: []
Sorted List: [1, 2, 3, 5, 8]
Descending Order List: [8, 5, 3, 2, 1]
Reversed List: [1, 2, 3, 5, 8]
Index of 2: 1
Count of 2: 2
Sum of numbers: 19
Min value: 1
Max value: 8
Copied List: [1, 2, 3, 5, 8]
12358
Index 0 -> 1
Index 1 -> 2
Index 2 -> 3
Index 3 -> 5
Index 4 -> 8
Squares: [1, 4, 9, 16, 25]
Even Numbers: [0, 2, 4, 6, 8]
Uppercase Fruits: ['APPLE', 'BANANA', 'CHERRY']

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:

1. Create tuples using different methods.


2. Access elements using indexing and slicing.
3. Demonstrate immutability by attempting to modify a tuple.
4. Perform tuple operations like concatenation, repetition, membership testing.
5. Use tuple unpacking and assignment.
6. Pass tuples as function arguments and return them from functions.
7. Use built-in tuple methods like count(), index().

PROGRAM: Tuple Operations in Python

# Creating tuples using different methods


tuple1 = (1, 2, 3, 4, 5)
tuple2 = ("apple", "banana", "cherry")
tuple3 = tuple([10, 20, 30, 40]) # Converting a list to a tuple
single_element_tuple = (42,) # Single-element tuple must have a comma

print("Tuple1:", tuple1)
print("Tuple2:", tuple2)
print("Tuple3:", tuple3)
print("Single-element Tuple:", single_element_tuple)

# Accessing tuple elements using indexing and slicing


print("First element of tuple1:", tuple1[0])
print("Last element of tuple1:", tuple1[-1])
print("Sliced Tuple1 (2nd to 4th element):", tuple1[1:4])

# 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)

# Tuple assignment and unpacking


a, b, c = (100, 200, 300) # Tuple assignment
print("Tuple Assignment - a:", a, "b:", b, "c:", c)

# Swapping values using tuple unpacking


x, y = 5, 10
x, y = y, x # Swapping using tuple unpacking
print("After Swapping - x:", x, "y:", y)

# Tuple as function arguments and return values


def calculate_sums(numbers):
return sum(numbers), max(numbers), min(numbers) # Returning multiple values as a tuple

result = calculate_sums(tuple1)
print("Sum, Max, Min from Tuple1:", result)

# Built-in Tuple Methods


sample_tuple = (1, 2, 3, 2, 4, 2, 5)
print("Count of 2 in sample_tuple:", sample_tuple.count(2))
print("Index of 4 in sample_tuple:", sample_tuple.index(4))
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

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.

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):


[Link] = title
[Link] = author
[Link] = True

def str (self):


return f"Title: {[Link]}\nAuthor: {[Link]}\nAvailable: {'Yes' if [Link] else 'No'}"

class Library:
def init (self):
[Link] = []
def add_book(self, book):
[Link](book)

print("Book added successfully.")

def display_books(self):
if not [Link]:
print("No books in the library.")
else:

for index, book in enumerate([Link], start=1):


print(f"Book {index}:")

print(book)

def borrow_book(self, title):


for book in [Link]:

if [Link]() == [Link]() and [Link]:


[Link] = False
print(f"{[Link]} borrowed successfully.")
return

print("Book not found or not available.")


0

def return_book(self, title):


for book in [Link]:

if [Link]() == [Link]() and not [Link]:


[Link] = True

print(f"{[Link]} 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.
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 add_material(name, quantity, price_per_unit):


"""Add a new material to the list"""
material = (name, quantity, price_per_unit)
[Link](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.
4.a) Set Operations and Built-in Methods in Python
AIM:
To write a Python program that demonstrates all the operations on sets, including:

 Set creation and initialization


 Adding and removing elements
 Mathematical set operations (union, intersection, difference, symmetric difference)
 Set comprehensions
 Set membership testing
 Iterating over a set
 Built-in methods available for sets

ALGORITHM:

1. Create sets using different methods.


2. Perform operations like adding, updating, and removing elements.
3. Perform set operations (union, intersection, difference, symmetric difference).
4. Use set comprehension to generate sets dynamically.
5. Check membership of elements in a set.
6. Iterate through set elements.
7. Demonstrate built-in set methods.

PROGRAM: Set Operations in Python

# Creating sets using different methods


set1 = {1, 2, 3, 4, 5}
set2 = {"apple", "banana", "cherry"}
set3 = set([10, 20, 30, 40]) # Converting a list to a set
empty_set = set() # Creating an empty set (not {} as it creates a dictionary)

print("Set1:", set1)
print("Set2:", set2)
print("Set3:", set3)
print("Empty Set:", empty_set)

# Adding and Removing elements


[Link](6)
[Link](["grape", "orange"]) # Adding multiple elements
[Link](3) # Removes 3 (raises an error if not found)
[Link](100) # Discard does not raise an error if element is absent
[Link]() # Removes a random element

print("Set1 after modifications:", set1)


print("Set2 after update:", set2)

# 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)

# Iterating over a Set


print("Elements in Set1:")
for item in set1:
print(item, end=" ")

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)

# Built-in Set Methods


sample_set = {1, 2, 2, 3, 4, 5}
print("Original Sample Set:", sample_set)
sample_set.clear() # Removes all elements from the set
print("After Clear:", sample_set)
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()

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:

1. Create dictionaries using different methods.


2. Perform operations like inserting, updating, and deleting key-value pairs.
3. Retrieve values using keys and get() method.
4. Iterate over dictionary keys, values, and items.
5. Demonstrate dictionary methods like pop(), popitem(), clear(), copy(), etc.
6. Use dictionary comprehension to generate a dictionary dynamically.
7. Work with nested dictionaries.

PROGRAM: Dictionary Operations in Python

# 1. Creating dictionaries using different methods


dict1 = {"name": "Alice", "age": 25, "city": "New York"}
dict2 = dict(country="USA", language="English")
empty_dict = {} # Empty dictionary

print("Dictionary 1:", dict1)


print("Dictionary 2:", dict2)
print("Empty Dictionary:", empty_dict)

# 2. Adding and updating key-value pairs


dict1["email"] = "alice@[Link]" # Adding a new key
dict1["age"] = 26 # Updating an existing key

print("Updated Dictionary 1:", dict1)

# 3. Accessing values using keys and get() method


print("Name:", dict1["name"])
print("City:", [Link]("city")) # Using get() avoids KeyError

# 4. Removing elements using pop() and popitem()


removed_value = [Link]("email") # Removes and returns value
print("Removed Email:", removed_value)
print("Dictionary after pop:", dict1)

[Link]() # Removes the last inserted item


print("Dictionary after popitem():", dict1)
# 5. Checking if a key exists
if "age" in dict1:
print("Age is present in the dictionary")

# 6. Iterating over dictionary


print("Keys in dict1:", list([Link]()))
print("Values in dict1:", list([Link]()))
print("Key-Value Pairs in dict1:", list([Link]()))

# 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

print("Copy of Dictionary:", dict_copy)


print("Dictionary after clear:", dict_methods)
OUTPUT:

Dictionary 1: {'name': 'Alice', 'age': 25, 'city': 'New York'}


Dictionary 2: {'country': 'USA', 'language': 'English'}
Empty Dictionary: {}
Updated Dictionary 1: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@[Link]'}
Name: Alice
City: New York
Removed Email: alice@[Link]
Dictionary after pop: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Dictionary after popitem(): {'name': 'Alice', 'age': 26}
Age is present in the dictionary
Keys in dict1: ['name', 'age']
Values in dict1: ['Alice', 26]
Key-Value Pairs in dict1: [('name', 'Alice'), ('age', 26)]
Squared Numbers Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionary: {'student1': {'name': 'Bob', 'age': 22, 'course': 'AI'}, 'student2': {'name': 'Charlie', 'age':
23, 'course': 'ML'}}
Copy of Dictionary: {'a': 1, 'b': 2, 'c': 3}
Dictionary after clear: {}

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)

print(f"Vehicle '{vehicle}' added to the inventory.")


def sell_vehicle(self, vehicle):
if vehicle in [Link]:
[Link](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 [Link]:
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 = [Link](*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
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:

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
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:

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
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

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
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]

# 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 [Link](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.
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.

PROGRAM: Implementing and Using Modules in Python

Step 1: Using Predefined Modules

import math # Importing math module


import random # Importing random module
import datetime # Importing datetime module
import os # Importing os module

# Using math module functions


print("Square root of 16:", [Link](16))
print("Factorial of 5:", [Link](5))
print("Value of Pi:", [Link])

# Using random module functions


print("Random number between 1 and 10:", [Link](1, 10))

# Using datetime module


current_time = [Link]()
print("Current Date and Time:", current_time)

# Using os module
print("Current Working Directory:", [Link]())

Step 2: Creating a User-Defined Module

Create a file named [Link] (User-defined module)

# [Link]
def greet(name):
return f"Hello, {name}! Welcome to Python Modules."
def add(a, b):
return a + b

# Demonstrate __name__ == "__main__"


if __name__ == "__main__":
print("This is mymodule running directly")
else:
print("mymodule has been imported")

Step 3: Importing and Using the User-Defined Module

Create another file named [Link]

# [Link]
import mymodule # Importing user-defined module

# Using functions from mymodule


print([Link]("Alice"))
print("Addition of 5 and 3:", [Link](5, 3))

# Importing specific function


from mymodule import greet
print(greet("Bob"))

# Importing with alias


import mymodule as mm
print([Link](10, 20))

# Importing all functions


from mymodule import *
print(greet("Charlie"))
OUTPUT:

When Running [Link]

mymodule has been imported


Hello, Alice! Welcome to Python Modules.
Addition of 5 and 3: 8
Hello, Bob! Welcome to Python Modules.
30
Hello, Charlie! Welcome to Python Modules.

When Running [Link] Directly

This is mymodule running directly

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:

# 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:
[Link]([Link]())
print("Content copied successfully.")

# Function to count words in a file


def count_words(file_name):
with open(file_name, 'r') as file:
content = [Link]()
word_count = len([Link]())
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 = [Link]()
words = [Link]()
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: [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.")

# 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.
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:

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 [Link]().
o Check the shape of the dataset using [Link].
o Check for missing values using [Link]().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 [Link] 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([Link]())
# Check the shape of the dataset

print("\nShape of the dataset:", [Link])

# Check for missing values


print("\nMissing values in the dataset:")

print([Link]().sum())

# Visualize the distribution of various features


[Link](figsize=(10, 6))
df['Label'].value_counts().plot(kind='bar', color='skyblue')
[Link]('Distribution of Email Labels')

[Link]('Label')
[Link]('Count')

[Link](rotation=45)
[Link]()

[Link](figsize=(10, 6))
df['Sender'].value_counts().head(10).plot(kind='bar', color='lightgreen')

[Link]('Top 10 Most Frequent Senders')


[Link]('Sender')
[Link]('Count')

[Link](rotation=45)
[Link]()

# Extract insights
print("\nInsights:")

print("Total number of emails:", [Link][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@[Link] alice@[Link]

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

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
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.

PROGRAM: Working with NumPy Arrays and Pandas DataFrames

Step 1: NumPy Array Operations

import numpy as np # Import NumPy

# Creating different types of NumPy arrays


arr1 = [Link]([1, 2, 3, 4, 5]) # 1D array
arr2 = [Link]((2, 3)) # 2D array of zeros
arr3 = [Link]((3, 3)) # 3D array of ones
arr4 = [Link](10, 21, 2) # Array with step values
arr5 = [Link](1, 10, 5) # 5 equally spaced values

# Performing array operations


sum_arr = arr1 + 5 # Broadcasting addition
mult_arr = arr1 * 2 # Broadcasting multiplication
dot_product = [Link](arr1, arr1) # Dot product

# 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))

# Reshaping and stacking


arr7 = [Link](1, 9) # Reshaping to 1x9
arr8 = [Link]((arr6, arr6)) # Vertical stacking
arr9 = [Link]((arr6, arr6)) # Horizontal stacking

Step 2: Pandas DataFrame Operations

import pandas as pd # Import Pandas

# Creating a DataFrame using a dictionary


data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'Salary': [50000, 60000, 70000, 80000]}
df = [Link](data)

# Displaying basic information


print([Link]()) # Display first few rows
print([Link]()) # Statistical summary

# Selecting specific columns


print(df[['Name', 'Salary']])

# Filtering rows
filtered_df = df[df['Age'] > 30] # Get employees older than 30

# Adding a new column


df['Bonus'] = df['Salary'] * 0.10

# Handling missing values


[Link][4] = ['Eve', [Link], 90000, [Link]] # Adding a row with missing values
[Link]([Link](), inplace=True) # Filling missing values with mean

# Grouping and aggregation


grouped = [Link]('Age')['Salary'].mean() # Grouping by Age
print(grouped)

# Reading from and writing to CSV


df.to_csv("employee_data.csv", index=False) # Saving to CSV
df_read = pd.read_csv("employee_data.csv") # Reading from CSV
print(df_read)
OUTPUT:

NumPy Array Operations Output

Sum: 450
Mean: 50.0
Max: 98
Min: 15

Pandas DataFrame Operations Output

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:

1. Import the NumPy library.


2. Perform appending values to the end of an array using the [Link]() 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 [Link]() and [Link]() 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 = [Link]([1, 2, 3])


array1 = [Link](array1, [4, 5, 6])

print("Appended array:", array1)


# Extract real and imaginary parts of an array of complex numbers
complex_array = [Link]([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 = [Link]([[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 = [Link](array2)
min_value = [Link](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.
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:

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 [Link]() method.
6. Delete the newly appended row using the [Link]() 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 = [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

new_row = {'name': 'Kate', 'score': 80, 'attempts': 3}


df_with_new_row = [Link](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.
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 :

Import the [Link] 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 [Link] function, passing the x positions, the popularity, and the labels as
arguments
Add some labels and a title to the chart using the [Link], [Link], and [Link] functions
Show the chart using the [Link] function

PROGRAM :

# Import the [Link] module as plt


import [Link] 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 [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:

Python library [Link] 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 [Link] 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]
[Link](marks_range, math_marks, label='Math marks', color='r')
[Link](marks_range, science_marks, label='Science marks', color='g')
[Link]('Scatter Plot')
[Link]('Marks Range')
[Link]('Marks Scored')
[Link]()
[Link]()
OUTPUT:

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:

To analyze and understand frequency distributions, measures of central tendency


(mean, median, mode), and measures of variability (standard deviation, variance,
range, IQR) using Python’s NumPy, Pandas, and Matplotlib libraries.

ALGORITHM:

A. Frequency Distribution

1. Load the dataset or create sample data.


2. Count the occurrences of unique values using value_counts().
3. Visualize the frequency distribution using a histogram and bar chart.

B. Averages (Measures of Central Tendency)

1. Calculate the Mean using mean().


2. Find the Median using median().
3. Determine the Mode using mode().

C. Variability (Measures of Dispersion)

1. Compute the Range (max - min).


2. Find the Variance using var().
3. Calculate Standard Deviation using std().
4. Determine Interquartile Range (IQR) (Q3 - Q1).
5. Visualize variability using Boxplot.

PROGRAM:

import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from scipy import stats

# Creating sample dataset


data = {'Scores': [78, 85, 90, 66, 75, 85, 95, 80, 85, 88, 92, 75, 90, 78, 85]}
df = [Link](data)

# **A. Frequency Distribution**


freq_dist = df['Scores'].value_counts() # Counting occurrences
print("Frequency Distribution:\n", freq_dist)

# Visualization: Histogram & Bar chart


[Link](figsize=(10,4))
[Link](1,2,1)
[Link](df['Scores'], bins=5, color='skyblue', edgecolor='black')
[Link]("Histogram of Scores")

[Link](1,2,2)
freq_dist.plot(kind='bar', color='salmon')
[Link]("Bar Chart of Frequency Distribution")
[Link]()

# **B. Averages (Measures of Central Tendency)**


mean_value = df['Scores'].mean()
median_value = df['Scores'].median()
mode_value = [Link](df['Scores'])[0][0]

print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Mode: {mode_value}")

# **C. Variability (Measures of Dispersion)**


range_value = df['Scores'].max() - 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}")

# **Boxplot for Variability**


[Link](figsize=(6,4))
[Link](y=df['Scores'], color='lightblue')
[Link]("Boxplot of Scores")
[Link]()
OUTPUT:

Frequency Distribution 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

Measures of Central Tendency Output

Mean: 83.13
Median: 85.0
Mode: 85

Measures of Variability Output

Range: 29
Variance: 56.04
Standard Deviation: 7.48
Interquartile Range (IQR): 10.0

Graphical Outputs

1. Histogram – Shows the distribution of scores.


2. Bar Chart – Displays the frequency of each score.
3. Boxplot – Highlights data spread, outliers, and variability.

RESULT:

The Python program for analyzing frequency distributions, averages, and


variability was successfully executed. It covered:
Frequency distributions with value_counts() and visualizations.
Measures of central tendency (mean, median, mode) using Pandas and SciPy.
Measures of variability (range, variance, standard deviation, and IQR).
Graphical analysis using Matplotlib and Seaborn.
15. Normal Curves, Correlation, and Scatter Plots

AIM:

To understand and implement normal distribution curves, correlation analysis,


and scatter plots using Python’s NumPy, Pandas, Matplotlib, and Seaborn
libraries.

ALGORITHM:

A. Normal Distribution Curve

1. Generate a dataset following a normal distribution using


[Link]().
2. Plot the probability density function (PDF) using Matplotlib.
3. Use [Link]() to overlay the theoretical normal curve.

B. Correlation Analysis

1. Create a dataset with two numerical variables.


2. Compute the correlation coefficient using .corr().
3. Use heatmap() from Seaborn to visualize correlation.

C. Scatter Plot

1. Plot the relationship between two variables using scatterplot().


2. Fit a regression line using regplot().
3. Analyze how data points are distributed.

PROGRAM:

import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from [Link] import norm

# **A. Normal Distribution Curve**


# Generating normally distributed data
mean, std_dev = 50, 10
data = [Link](mean, std_dev, 1000)

# Plot histogram of data


[Link](figsize=(10, 5))
[Link](data, bins=30, kde=True, color='skyblue')
[Link]("Normal Distribution Curve")
[Link]("Values")
[Link]("Frequency")
[Link]()
[Link]()

# **B. Correlation Analysis**


# Creating a sample dataset
[Link](42)
data = {'Age': [Link](20, 60, 100),
'Salary': [Link](30000, 100000, 100)}
df = [Link](data)

# 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]()

# **C. Scatter Plot**


[Link](figsize=(8, 5))
[Link](x=df['Age'], y=df['Salary'], color='green')
[Link]("Scatter Plot of Age vs Salary")
[Link]("Age")
[Link]("Salary")
[Link]()

# Regression Line
[Link](x=df['Age'], y=df['Salary'], scatter=False, color='red')
[Link]()
OUTPUT:

Normal Distribution Curve Output

1. Histogram with KDE (Kernel Density Estimate): A bell-shaped curve


indicating normally distributed data.

Correlation Analysis Output

Correlation Matrix:
Age Salary
Age 1.00 -0.02
Salary -0.02 1.00

2. Heatmap: Displays correlation coefficients between Age and Salary.

Scatter Plot Output

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().

You might also like