0% found this document useful (0 votes)
2 views104 pages

CCE Python Lab Observation

The document is a laboratory record notebook for students at Rajalakshmi Institute of Technology, detailing various Python programming experiments and objectives. It includes an index of topics covered, such as data types, control flow, functions, and data visualization using libraries like NumPy and Matplotlib. The course aims to develop proficiency in Python for real-world applications and data analysis.
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)
2 views104 pages

CCE Python Lab Observation

The document is a laboratory record notebook for students at Rajalakshmi Institute of Technology, detailing various Python programming experiments and objectives. It includes an index of topics covered, such as data types, control flow, functions, and data visualization using libraries like NumPy and Matplotlib. The course aims to develop proficiency in Python for real-world applications and data analysis.
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

RAJALAKSHMI INSTITUTE OF TECHNOLOGY

KUTHAMBAKKAM, CHENNAI - 600 124

Laboratory Record Note Book

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

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

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

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

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

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

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


INDEX
Name: Branch: Sec : Reg No.:

PAGE
S. DATE TITLE SIGNATURE
NO NO

Python Programming Basics – Data Types,


1a Control Flow, Functions, Strings, Lists, and
Tuples

1b List Operations and Built-in Methods in Python

1c Tuple Operations and Built-in Methods in 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 in


8
Python
INDEX
Name: Branch: Sec : Reg No.:

PAGE
S. NO DATE TITLE SIGNATURE
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


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

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

Page 2
[Link]: 1(a) Python Programming Basics – Data Types, Conditional Statements,

Date: Iteration Statements, Control Flow, Strings

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

1.1 Write a Python program to declare variables of different data types and display their types.

PROGRAM:
a=10
b="harish"
c=False
d=12.45
e=[24,52,False]
f=(12,41,"safd")
g={24:"harish"}
h={22}
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
OUTPUT:
10
harish
False
12.45
[24, 52, Fals]e
(12, 41, 'safd)'
{24: 'harish}'
{22}
<class 'int>'
<class 'str>'
<class 'bool>'
<class 'float>'
<class 'list>'
<class 'tuple>'
<class 'dict>'
<class 'set>'

Page 3
1.2 Write a Python program to demonstrate different types of type conversions (type casting).

PROGRAM:
a=12
C="24"
d="24.87"
print("Interger to float :",float(a))
b=12.7
print("float to integer:",int(b))
print("string to integer:",int(C))
print("integer to string :",str(a))
print("float to string :",str(b))

OUTPUT:
Interger to float : 12.0
float to integer: 12
string to integer: 24
integer to string : 12
float to string : 12.7

1.3 Write a Python program to create a simple calculatoar that performs addition, subtraction, multiplication,
Division, modulus and floor division using user input.

PROGRAM:

5print("simple calculator")
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
menu=int(input("which operation you like to perform \[Link]\[Link]\[Link]\[Link]\n
if menu == 1:
print("Addition of two numbers:",a+b)
elif menu ==2:
i (" b i f b " b)
print("Subtraction of two numbers:",a-b)
elif menu ==3:
print("Multiplication of two numbers:",a*b)
elif menu ==4:
print("Division of two numbers:",a/b)
elif menu ==5:
print("Modulus of two numbers:",a%b)
else:
print("Invalid input")
print("ThankYou")

def add(a,b):
print("Addition of two numbers:",a+b)

OUTPUT:
simple calculator
Enter first number:23
Enter second number:26
which operation you like to perform
[Link]
[Link]
[Link]
[Link]
[Link]
1
Addition of two numbers: 49
ThankYou

Page 4
1.4 Write a Python program to calculate the area and circumference of a circle.

PROGRAM:

r=float(input("Enter the radius of the circle"))


pi=3.14
print("The area of the circle is",pi*r*r)
print("circumference of circle is",2*pi*r)
OUTPUT:
Enter the radius of the circle3.7
The area of the circle is 42.9866
circumference of circle is 23.236

1.5 Write a Python program to calculate the Simple Interest.

PROGRAM:

p=float(input("Enter the principal amount"))


r=float(input("Enter the rate of interest"))
t=float(input("Enter the time period"))
print("The simple interest is",p*r*t/100)
OUTPUT:
Enter the principal amount10000
Enter the rate of interest2
Enter the time period4
The simple interest is 800.0

1.6 Write a Python program to find whether the given number is even or odd using only if statement and if ..
else Statement.

PROGRAM:

a=int(input("Enter the number"))


if a%2==0:
print("The given number is even")
else:
print("Thhe given number is odd")
OUTPUT:
Enter the number24
The given number is even

1.7 Develop a Python program to check whether the person is in teen age or not, using if...else statement.

PROGRAM:

age=int(input("Enter the age of the person"))


if age>12 and age<20:
print("The person is in teen age")
else:
print("The person is not in teen age")

OUTPUT:
Enter the age of the person14
The person is in teen age

Page 5
1.8 Develop a Python program to check whether the given year is leap year or not, using if...else statement

PROGRAM:

year=int(input("Enter the year to check whether year or not)")


if year%400==0:
print("The given year is leap year")
else:
print("The given year is not a leap year")

OUTPUT:
Enter the year to check whether year or not2005
The given year is not a leap year

1.9 Write a Python program to check if the number is positive or negative or zero using if….elif …else
statement.

PROGRAM:

num=int(input("Enter a number to check"))


if num >0:
print("Postive Number")
elif num<0:
print("Negative Number")
else:
print("Zero")
OUTPUT:
Enter a number to check-42
Negative Number

1.10 Write a Python program to find the biggest of 3 numbers using nested if...else statement.

PROGRAM:

a=int(input("Enter the first number"))


b=int(input("Enter the second number"))
c=int(input("Enter the third number"))
if a>b and a>c:
print("The biggest number is",a)
elif b>c:
print("The biggest number is",b)
else:
print("The biggest number is",c)

OUTPUT:
Enter the first number23
Enter the second number42
Enter the third number52
The biggest number is 52

Page 6
1.11 Develop Python program that will accept roll number, name and mark obtained by a student and assign
grades according to the following conditions, and display the roll number, name, mark and grade:

PROGRAM:
name=str(input("Enter the Name"))
roll=int(input("Enter the roll number"))
mark=int(input("Enter the mark obtained"))
print("Name:",name)
print("Roll Number:",roll)
print("Mark Obtained:",mark)
if mark>90:
print("Grade O")
elif mark>80 and mark<90:
print("Grade A")
elif mark>70 and mark<80:
print("Grade B")
elif mark>60 and mark<70:
print("Grade C")
elif mark>50 and mark<60:
print("Grade D")
else:
print("Grade E")
OUTPUT:
Enter the NameHarishkumar
Enter the roll number24
Enter the mark obtained64
Name: Harishkumar
Roll Number: 24
Mark Obtained: 64
Grade C

1.12 Develop a Python program to calculate electricity bill for domestic consumers as follows:

PROGRAM:
unit=float(input("Enter the total unit"))
if unit<100:
price= unit * 3
print("The electricity bill is",price)
elif unit>101 and unit <200:
price=unit*3.25
print("The electricity bill is",price)
elif unit>201 and unit < 500:
price=700+((unit-200)*4.60)
print("The electricity bill is",price)
elif unit>500:
price=2080+((unit-500)*6.60)
print("The electricity bill is",price)
OUTPUT:
Enter the total unit788
The electricity bill is 3980.8

Page 7
1.13 To create a menu-driven Python program that performs arithmetic operations.

PROGRAM:

choice=0
while choice != 8 :
print("Menu based Arithmetic operator")
menu=int(input("which operation you like to perform \[Link]\[Link]\[Link]\[Link]
if menu== 8:
break

a=int(input("Enter the value of a"))


b=int(input("Enter the value of b"))
if menu == 1:
print("Addition of two numbers:",a+b)
elif menu ==2:
print("Subtraction of two numbers:",a-b)
elif menu ==3:
print("Multiplication of two numbers:",a*b)
elif menu ==4:
print("Division of two numbers:",a/b)
elif menu ==5:
print("Modulus of two numbers:",a%b)
elif menu ==6:
print("Exponentiation of two numbers:",a**b)
elif menu ==7:
print("Floor division of two numbers:",a//b)
elif menu == 8:
print("Thank You for using. ")

OUTPUT:
Menu based Arithmetic operator
which operation you like to perform
[Link]
2. Subtraction
3. Multiplication
[Link]
[Link]
[Link]
7. Floor division
8. Exit
8

1.14 Write a python program to find sum of n numbers using while loop.

PROGRAM:

sum =0
n = int(input("Enter the number:"))
for i in range(1,n):
sum=sum+n
print(sum)
OUTPUT:
Enter the number:25
600

1.15 Write a python program to find factorial of a number using while loop.

PROGRAM:

Page 8
n=int(input("Factorial Number:"))
fact=1
while n!=0:
fact=fact*n
n=n-1
print(fact)

OUTPUT:
Factorial Number:5
120

1.16 Write a python program to find sum of digits of a number using while loop

PROGRAM:

digit = 0
num=int(input("Enter the number"))
n=num
while n>0:
digit = n%10
sum=sum+digit
n=n//10
print(sum)
OUTPUT:
Enter the number23
605

1.17 Write a python Program to Reverse the given number using while loop.

PROGRAM:

digit=int(input("Enter the number"))


n=digit
rev=0
while n>0:
rev=(rev*10)+(n%10)
n=n//10

print(rev)
OUTPUT:
Enter the number41
14

1.18 Write a python Program to find number is Armstrong number or not using while loop.

PROGRAM:

digit=int(input("Enter the number"))


n=digit
num=0
sum=0
while n>0:
num=n%10
cube=num*num*num
sum=cube+sum
n=n//10
if(sum==digit):
print("The given number is armstrong number")
else:
print("The given number is not armstrong number)"
OUTPUT:
Enter the number24
The given number is not armstrong number

Page 9
1.19 Write a python Program to check the number is palindrome or not using while loop.

PROGRAM:

digit=int(input("Enter the number"))


n=digit
rev=0
while n>0:
rev=(rev*10)+(n%10)
n=n//10

if digit == rev:
print("This is palindrome Number")
else:
print("This is not palindrome Number")
OUTPUT:
Enter the number111
This is palindrome Number

1.20 Write a python Program to print nos divisible by 5 not by 10 using for loop

PROGRAM:

n=int(input("Enter the range:"))


for i in range(1,n):
if(i%5==0) and (i%10!=0):
print(i)
OUTPUT:
Enter the range:100
5
15
25
35
45
55
65
75
85
95

1.21 Write a python Program to print fibonacci series using for loop

PROGRAM:

num=int(input("Enter the number"))


a,b=0,1
for _ in range(num):
print(a,end=" ")
a,b=b,a+b
Enter the number10
0 1 1 2 3 5 8 13 21 34

OUTPUT:

1.22 Write a python Program to find factors of a given number using for loop

Page 10
PROGRAM:

n=int(input("Enter the number"))


for i in range(1,n+1):
if n%i ==0:
print(i)
OUTPUT:
Enter the number24
1
2
3
4
6
8
12
24

1.23 Write a python program to check the given number is perfect number or not using for loop

PROGRAM:

n=int(input("Enter the number"))


sum=0
for i in range(1,n):
if n%i == 0:
sum=sum+i

if n==sum:
print("The number is perfect number")
else:
print("The number is not perfect number")
OUTPUT:
Enter the number52
The number is not perfect number

1.24 To create a menu-driven Python program to count the number of vowels, consonants, special character and
spaces in a given string.

PROGRAM:

word=str(input("Enter the word"))


count_b=0
count_a=0
count_d=0
count_c=0
n=len(word)
for i in word:
if i in "AEIOUaeiou":
count_b=1+count_b
else:
count_a=1+count_a
if i == " ":
count_c=1+count_c
elif not [Link]():
count_d=1+count_d
print(f"Number of vowels:{count_b}\nNumber of consonant:{count_a-(count_c + count_d)}\nNumber of spaces:{count
OUTPUT:
Enter the wordharish kumar
Number of vowels:4
Number of consonant:7
Number of spaces:1
Number of special character:0

Page 11
1.25 Write a Python program to simulate an ATM PIN verification system using control flow statements (break,
continue, and pass).

PROGRAM:
print("Welcome to testing ATM PIN Verification test..)"
pin=1234
chance =0
while chance != 5:
print("Enter the PIN")
check=int(input())
if check != pin:
print("Try again")
chance=chance+1
else:
print("Correct PIN")
break

OUTPUT:
Welcome to testing ATM PIN Verification test..
Enter the PIN
1234
Correct PIN

Page 12
[Link]: 1(b) List Operations and Built-in Methods in Python

Date:

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

Page 13
Page 14
Page 15
Page 16
Page 17
[Link]: 1(C) Tuple Operations and Built-in Methods in Python

Date:

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:

Page 18
Page 19
Page 20
Page 21
Page 22
[Link] 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.

Page 23
Page 24
Page 25
Page 26
[Link] 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 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.

Page 27
Page 28
Page 29
Page 30
Page 31
[Link] (a) 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.

Page 32
Page 33
Page 34
Page 35
Page 36
[Link](b) 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.

PROGRAM:

Page 37
Page 38
Page 39
Page 40
Page 41
[Link] 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.

Page 42
Page 43
Page 44
Page 45
Page 46
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:

Page 47
Page 48
Page 49
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:

Page 50
Page 51
Page 52
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:

Page 53
Page 54
Page 55
Page 56
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:

Page 57
Page 58
Page 59
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

Page 60
Step 2: Creating a User-Defined Module

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

Page 61
Step 3: Importing and Using the User-Defined

Module Create another file named [Link]

Page 62
OUTPUT:

When Running [Link]

When Running [Link]

Directly

RESULT:

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

Page 64
Page 65
Page 66
Page 67
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:

Page 68
Page 69
Page 70
Page 71
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:

Page 72
Page 73
Page 74
Page 75
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

Page 76
Page 77
Step 2: Pandas DataFrame Operations

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

Page 79
Page 80
Page 81
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:

Page 82
Page 83
Page 84
13a). BASIC PLOTS USING MATPLOTLIB (DEMONSTRATE
VARIOUS STYLES OF PLOTTING GRAPH)
Aim

To 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 [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] function
 Show the chart using the [Link] function

PROGRAM :

Page 85
Page 86
Page 87
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:

Page 88
Page 89
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.

Page 90
PROGRAM:

Page 91
Page 92
Page 93
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:

Page 94
Page 95
Page 96
Page 97
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:

You might also like