0% found this document useful (0 votes)
16 views

Ad23221 Python for Data Science Record

The document is a laboratory record notebook for students at Rajalakshmi Institute of Technology, detailing various Python programming exercises and experiments. It includes sections for student information, a bonafide certificate, an index of experiments, and specific programming tasks related to data types, control flow, functions, and list operations. Each exercise outlines the aim, algorithm, program code, and expected output for practical assessments.

Uploaded by

sheshanth
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)
16 views

Ad23221 Python for Data Science Record

The document is a laboratory record notebook for students at Rajalakshmi Institute of Technology, detailing various Python programming exercises and experiments. It includes sections for student information, a bonafide certificate, an index of experiments, and specific programming tasks related to data types, control flow, functions, and list operations. Each exercise outlines the aim, algorithm, program code, and expected output for practical assessments.

Uploaded by

sheshanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

RAJALAKSHMI INSTITUTE OF TECHNOLOGY

KUTHAMBAKKAM, CHENNAI - 600 124

Laboratory Record Note Book

NAME .............................................................................................................

SUBJECT ..........................................................................................................

BRANCH ...........................................................................................................

REGISTER No. ...............................................................................

ROLL No ........................................................................................

SEMESTER ..........................................................................................................

ACADEMIC YEAR .............................................................................................


RAJALAKSHMI INSTITUTE OF TECHNOLOGY
KUTHAMBAKKAM, CHENNAI - 600 124

BONAFIDE CERTIFICATE

Signature Signature
Faculty - in - Charge H.O.D

Submitted for the Practical Examination held on............................................

Internal Examiner External Examiner


INDEX
Name:_________________ Branch:______ Sec :___ Reg No.:_________
PAGE
S. NO DATE TITLE SIGNATURE
NO
Python Programming Basics – Data Types,
1a Control Flow, Functions, Strings, Lists, and
Tuples

1b List Operations and Built-in Methods in Python

Tuple Operations and Built-in Methods in


1c
Python

Implementation of Library management using


2
List

Implementation of construction material


3
management using list

4a Set Operations and Built-in Methods in Python

Dictionary Operations and Built-in Methods in


4b
Python

5 Implementing real-time applications using Sets

Implementing programs using Functions


6a
Factorial

Implementing programs using Functions using


6b
largest number in a list

Implementing programs using Functions using


6c
area of shape

7 String Functions Using Python

Implementing Programs Using Written Modules


8
in Python
INDEX
Name:_________________ Branch:______ Sec :___ Reg No.:_________
9 Program for File using Python

10 Program for Exception Handling

11 Program for Exploratory Data Analysis

Working with NumPy Arrays and Pandas


12 a
DataFrames

12 b Program for Numpy Array

12 c Program for Pandans Data Frame

Basic Plots Using Matplotlib (Demonstrate


13 a
Various Styles Of Plotting Graph)

Write a Python program to draw a scatter plot


13 b comparing two subject marks of Mathematics
and Science. Use marks of 10 students.

Write a Python programming to create a pie


chart of gold medal achievements of five most
13 c
successful countries in 2016 Summer Olympics.
Read the data from a csv file.

Frequency Distributions, Averages, and


14
Variability

15 Normal Curves, Correlation, and Scatter Plots


EX. NO. 1a) Python Programming Basics – Data Types Control
Flow, Functions, Strings, Lists and Tuples
DATE:

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

2
Step 3: Using Iterative Statement

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

3
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

4
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.")

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

Output:

Enter the number of terms: 7


0112358
5
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))

Output:

Enter a number: 5 Factorial


of 5 is 120

6
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 char.isalpha(): consonant_count
+= 1
elif char.isspace():
space_count +=
1

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

Output:

Enter a string: Hello World


Vowels: 3
Consonants: 7
Spaces: 1

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


numbers.append(10)
numbers.remove(2)
numbers.sort()

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

8
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

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:

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

11
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
numbers.append(6) # Adding element at end
numbers.insert(2, 50) # Inserting at a position
numbers.extend([7, 8, 9]) # Extending the list

print("Updated Numbers List:",

numbers) # Removing Elements


numbers.pop() # Removes last element
numbers.remove(50) # Removes first occurrence
of 50 del numbers[1] # Deletes element at index 1
numbers.clear() # Clears the list
print("Numbers List after Deletion:",
numbers) # Recreating numbers list
numbers = [5, 2, 8, 3, 1]

# Sorting and Reversing


numbers.sort() # Sorts in ascending order
print("Sorted List:", numbers)
numbers.sort(reverse=True) # Descending
order print("Descending Order List:",
numbers)
12
numbers.reverse() # Reverses the list
print("Reversed List:", numbers)

# Searching and Counting Elements


numbers.append(2)
print("Index of 2:",
numbers.index(2)) print("Count of
2:", numbers.count(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 = 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}")

# 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 = [fruit.upper() for fruit
in fruits]
print("Squares:", squares)
print("Even Numbers:", even_numbers)
print("Uppercase Fruits:", uppercase_fruits)

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

14
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 technique.
15
EX. NO. 1c) Experiment: Tuple Operations and Built-in Methods
DATE: 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().

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

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)

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

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:

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

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:

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

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("No books in the library.")


else:
for index, book in enumerate(self.books,
start=1): print(f"Book {index}:")

print(book)

def

borrow_boo

k(self, title):

for book in

self.books:

if book.title.lower() == title.lower() and

book.available: book.available = False

22
print(f"{book.title} borrowed successfully.")
return

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

def

return_book(self,

title): for book in

self.books:

if book.title.lower() == title.lower() and not

book.available: book.available = True

print(f"{book.title} returned

successfully.") return

print("Book not found or already returned.")

def main():

library =

Library()

while True:

print(“\nLibrary Management System”)


print(“1.Add Book”)

print(“2.Display Book”)

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:


23
") 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("Exi

ting the

program."

) break

else:

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

if__name__==”__main__”:
main()

24
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

25
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

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

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:

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.

29
Program:
# Initialize an empty list to store construction

materials materials = []

def add_material(name, quantity,

price_per_unit): """Add a new

material to the list"""

material = (name, quantity, price_per_unit)

materials.append(material)

print(f"{name} added to the materials

list.") def update_material(name,

quantity,

price_per_unit): """Update an existing

material in the list"""

for i, material in

enumerate(materials):

if material[0]

== name:

materials[i] = (name, quantity,

price_per_unit) print(f"{name}

updated in the materials list.") return

print(f"{name} not found in the materials list.")

def display_materials():

"""Display all materials in the

list""" if not materials:

print("No materials

found.") else:

30
print("Material

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

31
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.")

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

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

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:

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

36
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


set1.add(6)
set2.update(["grape", "orange"]) # Adding multiple elements
set1.remove(3) # Removes 3 (raises an error if not found)
set1.discard(100) # Discard does not raise an error if element is
absent set1.pop() # 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
37
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)

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:

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

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:

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.

41
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"] = "[email protected]" # 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:", dict1.get("city")) # Using get() avoids KeyError

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


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

dict1.popitem() # 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(dict1.keys()))
print("Values in dict1:", list(dict1.values()))
print("Key-Value Pairs in dict1:",
list(dict1.items()))

# 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

print("Copy of Dictionary:", dict_copy)


print("Dictionary after clear:", dict_methods)

43
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': '[email protected]'}
Name: Alice
City: New York
Removed Email: [email protected]
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: {}

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

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.

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.

46
Program:
class

Automobile: def
init (self):

self.catalog = set()
self.inventory = set()
self.customer_preferen
ces = {}

def add_model_to_catalog(self, model):


self.catalog.add(model)

print(f"Model '{model}' added to the


catalog.") def
remove_model_from_catalog(self, model):

if model in self.catalog:
self.catalog.remove(model)

print(f"Model '{model}' removed from the


catalog.") else:

print(f"Model '{model}' not found in the


catalog.") def display_catalog(self):

print("Vehicle
Catalog:") for
model in
self.catalog:

print("-", model)
def add_vehicle_to_inventory(self, vehicle): self.inventory.add(vehicle)
print(f"Vehicle '{vehicle}' added to the
inventory.") def sell_vehicle(self, vehicle):

if vehicle in self.inventory:
self.inventory.remove(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.")

def update_customer_preference(self, customer,


new_models): if customer in
self.customer_preferences:

self.customer_preferences[customer].update(new_models)
print(f"Customer '{customer}' preferences updated
successfully.")

else:
print(f"Customer '{customer}' not found in the
preferences.") def common_preferences(self):

common_pref = set.intersection(*self.customer_preferences.values())

print("Common Customer Preferences:")

for model in

common_pref:
print("-", model)

def main():
auto =
Automobile()
# Populate
initial data

auto.add_model_to_catalog("SUV")
auto.add_model_to_catalog("Sedan")
auto.add_model_to_catalog("Hatchback")
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")

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_inve
ntory() elif choice
== '3':

print("\nCustomer Preference Analysis:")


auto.add_customer_preference(input("Enter
customer name: "),
49
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("Exi
ting the
program."
) break

else:
print("Invalid choice. Please enter a number from 1 to 4.")

if_ _ name__== " __main__ ":


main()

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

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:

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.

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

57
output:

Enter numbers separated by space: 20 1 300 50


The largest number in the list is 300

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:

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.

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

def rectangle_area(length, width):


return length * width

def triangle_area(base, height):


return 0.5 * base * height

def main():
print("Calculate Area of Shapes:")
print("1. Circle")
print("2. Rectangle")
print("3. Triangle")

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

if choice == '1':
try:
radius = float(input("Enter the radius of the circle: "))
print(f"The area of the circle is {circle_area(radius)}.")
except ValueError:
print("Invalid input. Please enter a numeric value for the radius.")

elif choice == '2':


try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
print(f"The area of the rectangle is {rectangle_area(length, width)}.")
except ValueError:
print("Invalid input. Please enter numeric values for length and width.")

elif choice == '3':


try:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

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.

Calculate Area of Shapes:


1. Circle
2. Rectangle
3. Triangle
Enter your choice (1/2/3): 3
Enter the base of the triangle: 7
Enter the height of the triangle: 4
The area of the triangle is 14.0.

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.

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.

63
Program:
# Function to reverse a string

def reverse_string(string):

return string[::-1]

# Function to check if a string is a palindrome

def is_palindrome(string):

return string == string[::-1]

# Function to count characters in a string

def count_characters(string):

char_count = {}

for char in string:

char_count[char] = char_count.get(char, 0) + 1

return char_count

# Function to replace characters in a string

def replace_characters(string, old_char, new_char):

return string.replace(old_char, new_char)

def main():

while True:

print("\nMenu:")

print("1. Reverse a string")

print("2. Check if a string is palindrome")

print("3. Count characters in a string")

print("4. Replace characters in a string")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':

string = input("Enter a string: ")

print("Reversed string:", reverse_string(string))

elif choice == '2':

string = input("Enter a string: ")


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

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:

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.

69
PROGRAM: Implementing and Using Modules in

Python Step 1: Using Predefined Modules

# Importing predefined modules


import math
import random
import datetime
import os

# Using math module


print("Square root of 16:", math.sqrt(16))
print("Factorial of 5:", math.factorial(5))
print("Value of Pi:", math.pi)

# Using random module


print("Random number between 1 and 10:", random.randint(1, 10))

# Using datetime module


current_time = datetime.datetime.now()
print("Current Date and Time:", current_time)

# Using os module
print("Current Working Directory:", os.getcwd())

70
Step 2: Creating a User-Defined Module

Create a file named mymodule.py (User-defined module)

# mymodule.py

def greet(name):

return f"Hello, {name}! Welcome to Python Modules."

def add(a, b):

return a + b

if __name__ == "__main__":

print("This is mymodule running directly")

else:

print("mymodule has been imported")

71
Step 3: Importing and Using the User-Defined Module

Create another file named main.py

# main.py
import mymodule # Importing user-defined module

# Using functions from mymodule


print(mymodule.greet("Alice"))
print("Addition of 5 and 3:", mymodule.add(5, 3))

# Importing specific function


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

# Importing with alias


import mymodule as mm
print(mm.add(10, 20))

# Importing all functions (not recommended generally)


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

72
OUTPUT:

When Running main.py


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

Directly This is mymodule running

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:

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.

75
Program:

# Function to copy content from one file to another


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

# Function to count words in a file


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

# Function to find the longest word in a file


def longest_word(file_name):
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
if not words:
return "No words in file."
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: ")

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

# Proper name check


if __name__ == "__main__":
main()

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:

1. Copy content from one file to another


2. Count words in a file
3. Find the longest word in a file
4. Exit
Enter your
choice: 2
Enter file
name:

destination.txt
Number of words
in the file: 9

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

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

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

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

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

# Proper entry point check


if __name__ == "__main__":
main()

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:

1. Export emails as a dataset:


o Collect email data from the email service provider or email client.
o Save the email data as a CSV file or in any other suitable format.

2. Import the dataset into a pandas DataFrame:


o Use the pandas.read_csv() function to read the CSV file into a DataFrame.

3. Perform exploratory data analysis:


o Explore the dataset by displaying the first few rows using DataFrame.head().
o Check the shape of the dataset using DataFrame.shape.
o Check for missing values using DataFrame.isnull().sum().
o Analyze the distribution of various features using histograms, bar plots, etc.
o Extract insights based on the analysis.

86
Program:
import pandas as pd
import matplotlib.pyplot as plt

# Function to perform exploratory data analysis on email dataset


def perform_eda(email_dataset):
# Read the dataset into a DataFrame
df = pd.read_csv(email_dataset)
# Display the first few rows of the dataset
print("First few rows of the dataset:")
print(df.head())

# Check the shape of the dataset


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

# Visualize the distribution of email labels


plt.figure(figsize=(10, 6))
df['Label'].value counts().plot(kind='bar', color='skyblue')
plt.title('Distribution of Email Labels')
plt.xlabel('Label')

plt.ylabel('Count')

plt.xticks(rotation=45)
plt.show()

# Visualize top 10 most frequent senders


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

plt.ylabel('Count')

plt.xticks(rotation=45)
plt.show()

87
# Extract insights

print("\nInsights:")

print("Total number of emails:", df.shape[0])


print("Total number of unique senders:", df['Sender'].nunique())
print("Total number of unique recipients:", df['Recipient'].nunique())
print("Average number of emails per sender:", df['Sender'].value_counts().mean())
print("Average number of emails per recipient:", df['Recipient'].value_counts().mean())
# Main function

def main():

email_dataset = "email_dataset.csv" # Make sure this file exists in your directory


perform_eda(email_dataset)

# Entry point

if __name__ == "__main__":
main()

88
OUTPUT:

First few rows of the dataset: sender Receipt \ [email protected] [email protected]

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

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

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:

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

91
PROGRAM: Working with NumPy Arrays and Pandas

DataFrames # Step 1: NumPy Array Operations

import numpy as np

# Creating different types of NumPy arrays

arr1 = np.array([1, 2, 3, 4, 5]) # 1D array

arr2 = np.zeros((2, 3)) # 2D array of zeros

arr3 = np.ones((3, 3)) # 3D array of ones

arr4 = np.arange(10, 21, 2) # Array with step values

arr5 = np.linspace(1, 10, 5) # 5 equally spaced values

# Performing array operations

sum_arr = arr1 + 5

mult_arr = arr1 * 2

dot_product = np.dot(arr1, arr1)

# Aggregation functions

arr6 = np.random.randint(1, 100, (3, 3))

print("Random Array (arr6):\n", arr6)

print("Sum:", np.sum(arr6))

print("Mean:", np.mean(arr6))

print("Max:", np.max(arr6))

print("Min:", np.min(arr6))

# Reshaping and stacking

arr7 = arr6.reshape(1, 9)

arr8 = np.vstack((arr6, arr6))


92
arr9 = np.hstack((arr6, arr6))

# Step 2: Pandas DataFrame Operations

import pandas as pd

# Creating a DataFrame using a dictionary

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David'],

'Age': [25, 30, 35, 40],

'Salary': [50000, 60000, 70000, 80000]

df = pd.DataFrame(data)

# Displaying basic information

print("\nDataFrame Head:\n", df.head())

print("\nStatistical Summary:\n", df.describe())

# Selecting specific columns

print("\nSelected Columns:\n", df[['Name', 'Salary']])

# Filtering rows

filtered_df = df[df['Age'] > 30]

print("\nFiltered Rows (Age > 30):\n", filtered_df)

# Adding a new column

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

# Handling missing values

df.loc[4] = ['Eve', np.nan, 90000, np.nan]

df.fillna(df.mean(numeric_only=True), inplace=True)

93
# Grouping and aggregation

grouped = df.groupby('Age')['Salary'].mean()

print("\nGrouped by Age (Salary Mean):\n", grouped)

# Reading from and writing to CSV

df.to_csv("employee_data.csv", index=False)

df_read = pd.read_csv("employee_data.csv")

print("\nData Read from CSV:\n", df_read)

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

Filtered Rows (Age > 30):


Name Age Salary
2 Charlie 35 70000
3 David 40 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

Data Read from CSV:


Name Age Salary Bonus
0 Alice 25.0 50000 5000.00
1 Bob 30.0 60000 6000.00
2 Charlie 35.0 70000 7000.00
3 David 40.0 80000 8000.00
4 Eve 32.5 90000 6500.00

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:

1. Import the NumPy library.


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

98
Program:

import numpy as np

# Function to perform various operations with NumPy arrays

def numpy_operations():

# Append values to the end of an array

array1 = np.array([1, 2, 3])

array1 = np.append(array1, [4, 5, 6])

print("Appended array:", array1)

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

complex_array = np.array([1+2j, 3+4j, 5+6j])

real_parts = complex_array.real

imaginary_parts = complex_array.imag

print("\nReal parts of complex array:", real_parts)

print("Imaginary parts of complex array:", imaginary_parts)

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

array2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

second_column = array2[:, 1]

print("\nSecond column elements of array2:", second_column)

# Find the maximum and minimum value from the shape of (3,3) array

max_value = np.max(array2)

min_value = np.min(array2)

print("\nMaximum value:", max_value)

print("Minimum value:", min_value)

# Main function

def main():

numpy_operations()

if __name__ == "__main__":

main()

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

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:

1. Import the Pandas library.


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

101
Program:
import pandas as pd

# Function to perform operations with Pandas DataFrame


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

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

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

# Append a new row 'Kate' to the DataFrame


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

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

DataFrame sorted by 'name' in descending order, then by 'score' in ascending order:


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

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


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

DataFrame with the new row 'Kate' 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

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 :

• Import the matplotlib.pyplot module as plt


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

105
PROGRAM :

# Import the matplotlib.pyplot module as plt


import matplotlib.pyplot as plt
# Define a list of programming languages and a list of their popularity
languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8.0, 7.7, 6.7]

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

# Plot the bars using the plt.barh function


plt.barh(x_pos, popularity, tick_label=languages)

# Add labels and a title to the chart


plt.xlabel('Popularity')
plt.ylabel('Languages')
plt.title('Popularity of Programming Languages')

# Show the chart


plt.show()

106
OUTPUT:

RESULT:

Thus the program is executed successfully and output is verified.

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:

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

▪ Two random variables are taken with random values. The scatter function

plots a scatter plot. The scatter function takes 2 arguments and a label

variable gives the label to the plot.

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

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

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.

Sample data: medal.csv


country, gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17

AIM:

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

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

# Reading data from the CSV file


df = pd.read_csv('medal.csv')

# Extracting country names and medal counts


country_data = df["country"]
medal_data = df["gold_medal"]

# Setting colors for each country in the pie chart


colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]

# Exploding the first slice to highlight it


explode = (0.1, 0, 0, 0, 0)

# Creating the pie chart


plt.pie(medal_data, labels=country_data, explode=explode, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=140)

# Adding a title
plt.title("Gold Medal Achievements of Five Most Successful\nCountries in the 2016 Summer
Olympics")

# Displaying the pie chart


plt.show()

112
OUTPUT:

RESULT:
Thus the program is executed successfully and output is verified.

113
EX. NO. 14 Frequency Distributions, Averages, and Variability

DATE:

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.

114
PROGRAM:
import numpy
as np import
pandas as pd
import matplotlib.pyplot 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 = pd.DataFrame(data)

# **A. Frequency Distribution**


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

# Visualization: Histogram & Bar


chart plt.figure(figsize=(10,4))
plt.subplot(1,2,1)
plt.hist(df['Scores'], bins=5,
color='skyblue', edgecolor='black')
plt.title("Histogram of Scores")

plt.subplot(1,2,2)
freq_dist.plot(kind='bar', color='salmon')
plt.title("Bar Chart of Frequency Distribution")
plt.show()

# **B. Averages (Measures of Central


Tendency)** mean_value =
df['Scores'].mean()
median_value = df['Scores'].median()
mode_value =
stats.mode(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() -

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}")

# **Boxplot for Variability**


plt.figure(figsize=(6,4))
sns.boxplot(y=df['Scores'], color='lightblue')
plt.title("Boxplot of Scores")
plt.show()

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

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

118
EX. NO. 15 Normal Curves, Correlation, and Scatter Plots

DATE:

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 numpy.random.normal().
2. Plot the probability density function (PDF) using Matplotlib.
3. Use scipy.stats.norm.pdf() 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.

119
PROGRAM:

import numpy
as np import
pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm

# **A. Normal Distribution Curve**


# Generating normally distributed
data mean, std_dev = 50, 10
data = np.random.normal(mean, std_dev, 1000)

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

# **C. Scatter Plot**


plt.figure(figsize=(8, 5))
120
sns.scatterplot(x=df['Age'], y=df['Salary'],
color='green') plt.title("Scatter Plot of Age vs
Salary")
plt.xlabel("Age")
plt.ylabel("Salary")
plt.grid()

# Regression Line
sns.regplot(x=df['Age'], y=df['Salary'], scatter=False,
color='red') plt.show()

121
OUTPUT:

Normal Distribution Curve Output

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


curve indicating normally distributed data.

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

122
Correlation Analysis Output

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

Scatter Plot Output

3. Scatter plot with regression line: Shows the relationship


between Age and Salary.

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

You might also like