0% found this document useful (0 votes)
35 views92 pages

AI&DS PYTHON Lab Record

The document outlines the curriculum for the Python Programming Laboratory course at Adithya Institute of Technology, focusing on practical applications in Python for the academic year 2024-2025. It includes various experiments involving flowchart development, basic Python programming, and real-time applications using lists, functions, and file handling. The document also specifies the assessment structure, including internal and external examination details.

Uploaded by

jemimaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views92 pages

AI&DS PYTHON Lab Record

The document outlines the curriculum for the Python Programming Laboratory course at Adithya Institute of Technology, focusing on practical applications in Python for the academic year 2024-2025. It includes various experiments involving flowchart development, basic Python programming, and real-time applications using lists, functions, and file handling. The document also specifies the assessment structure, including internal and external examination details.

Uploaded by

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

ADITHYA INSTITUTE OF TECHNOLOGY

COIMBATORE - 641107

U24GE3106-PYTHON PROGRAMMING LABORATORY

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

REGULATION 2024
Academic Year: 2024-
2025 Year/Semester:
I/01

1
BONAFIDE CERTIFICATE

Certified that this is the bonafide record of work done by Mr /

Ms……………........ Reg.No of Semester Electronics and Communication

Engineering

Branch during theAcademic Year……

Place:

Date :

Staff-In-Charge Head of the department

Submitted for the university practical examination held on ……………….

2
Internal Examiner External Examiner

3
INDEX

Page
Date Experiment Name Mark Signature
Number

Identification and solving of simple real life or


scientific or technical problems, and
developing flow charts for the same.
1 (Electricity Billing, Retail shop billing, Sin
series, weight of a motorbike, Weight of a steel
bar, compute Electrical Current in Three
Phase AC Circuit, etc.)

1 (a) Flowchart for Electricity Bill Calculation

1 (b) Flowchart for retail shop bill calculation

1(c) Flowchart for computing sin series

1(d) Flowchart for calculating the weight of a Steelbar

Flowchart for calculating the compute Electrical


1(e)
Current in Three Phase AC Circuit

Python programs using simple statements and


2
expressions

2(a) Exchange the value of two variables

4
2(b) Circulate ‘n’ values

2(c) Distance between two points

Scientific problems using Conditionals and


3 Iterative loops.

3(a) Number series

3(b) Number Pattern

3(c) Print pyramid Patterns in python

Implementing real-time/technical applications


4
using Lists.

Basic Operations (Insertion, Updating, deletion,


4(a)
accessing, List Comprehensions)

Implement linear search and binary search using


4(b)
list

4(c) Matrix operations using Nested List

4(d) Implement Merge, Bubble and Insertion sort

create a tuple and perform its operations for


5
the following:

5
Basic Operations (Insertion, Updating, deletion,
5(a)
accessing)

5(b) Items present in a library

5(c) Components of a car

Materials required for construction of a


5(d)
laboratory

6 Implementing basic operations on Sets

6(a) Membership

6(b) Operations

6(c) Modifications

7 Operations of Dictionaries

Python program to create a dictionary with


7(a) integer keys, and print the keys, values & key-
value pairs

Python program to randomize (shuffle) values of


7(b)
dictionary

8 Implementing programs using Functions.

6
8(a) Factorial

8(b) largest number in a list

8(c) Area of shape

9 Implementing programs using Strings

9(a) Reverse

9(b) Palindrome

9(c) Character count

9(d) Replacing characters

Implementing programs using written


10 modules and Python Standard Libraries
(pandas, numpy, matplotlib, scipy

10(a) Simple Program using numpy

10(b) Program using pandas

10(c) Using Scipy - Univariate Interpolation

7
Implementing real-time/technical applications
11
using file handling

Python program to copy the content of one file


11(a)
into another file

Python Program to Count the Number of Words


11(b)
in a Text File

Python Program to find longest Word in a Text


11(c)
File

Implementing real-time / technical


12
applications using Exception handling

12(a) Divide by zero error

12(b) Voter’s age validity

12(c) Student mark range validation

Python programs using Time and Calendar


13
related functions.

13(a) Print the current time using time module

Display the calendar of given month of the year


13(b)
using calendar

8
Exp No.1 Identification and solving of simple real life or scientific or technical
problems, and developing flow charts for the same. (Electricity Billing, Retail
shop billing, Sin series, weight of a motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)

Exp no: 1.a) Flowchart for Electricity Bill

Calculation AIM:

To draw the flowchart for electricity bill calculation with the following rates for its

customers: -

No. of unit consumed Charges/unit

(RM) 1-200 2.50

201 - 500 3.50

over 501 5.00

Draw a flowchart to calculated the net amount of the bill for each consumer and print it.

ALGORITHM:

Step 1: Start

Step 2: Read the unit values

Step 3: Check

1<=unit<=200

Then calculate total_charges=unit*2.50

Step 4: Check 201<=unit<=500

Then calculate total_charges=unit*3.50

9
Step 5: Check unit>500

Then calculate total_charges=unit*5.0

Step 6: print total_charges

Step 7: Stop

FLOWCHART:

10
Exp No: 1) b. Flowchart for retail shop bill

calculation AIM:

To draw a flowchart for retail bill preparation

ALGORITHM:

Step 1: Start

Step 2: Read item name

Step 3: Read price per unit

Step 4: Read No of

Quantity

Step 5: Compute Totalcost=Quantity*price per

unit Step 6: Display total

Step 7: Read payment

Step 8: Compute paychange=payment-Totalcost

Step 9: Display the items,payment and paychange

Step 10: Stop

11
FLOWCHART:

12
Exp No: 1) c. Flowchart for computing sin series

AIM:

To draw a flowchart for computing sin series

ALGORITHM:

Step 1: Take in the value of x in degrees and the number of terms and store it in separate

variables.

Step 2: Pass these values to the sine function as arguments.

Step 3: Define a sine function and using a for loop, first convert degrees to radians.

Step 4: Then use the sine formula expansion and add each term to the sum

variable. Step 5: Then print the final sum of the expansion.

Step 6: Stop

13
FLOWCHART:

14
Exp No: 1) d. Flowchart for calculating the weight of a motorbike

AIM:

To draw a flowchart for weight of a motorbike.

ALGORITHM:

Step 1: Start

Step 2: Read

D,L

Step 3: Compute w=D**2L/162

Step 4: Print w

Step 5:

Stop

FLOWCHART:

15
Exp No: 1) e. Flowchart for calculating the weight of a Steelbar

AIM:

To draw a flowchart for weight of a steel bar

ALGORITHM:

Step 1: Start
Step 2: Read LBS
Step 3: Compute w=LBS/2.2046
Step 4: Print w
Step 5: Stop
FLOWCHART:

16
Exp No : 1) f. Flowchart for calculating the compute Electrical Current in Three Phase

AC Circuit

AIM :

To draw a flowchart for compute Electrical Current in Three Phase AC Circuit

ALGORITHM :

Step 1: Start
Step 2: Read kva,voltage
Step 3: Compute current=kva/voltage
Step 4: Print current
Step 5: Stop
FLOWCHART:

RESULT:

Thus the flow charts were successfully drawn the above concept of (Electricity Billing,
Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)

17
Exp No. 2 PYTHON PROGRAMS USING SIMPLE STATEMENTS AND
EXPRESSIONS

AIM:

To write python programs using simple statements and expressions. These Python
programs perform basic tasks like calculating the sum of two numbers, checking if a number is
even or odd, computing the area of a circle using πr², finding the largest of three numbers, and
reversing a string. They demonstrate essential operations like arithmetic, conditional checks, and
string manipulation.

2(a). Exchange the value of two

variables ALGORITHM:

STEP 1: Read the values of P and


Q STEP 2: temp = P
STEP 3: P = Q
STEP 4: temp = P
STEP 5: PRINT P,
Q
PROGRAM:

P = int( input("Please enter value for P: "))


Q = int( input("Please enter value for Q: "))
temp= P
P=Q
Q = temp
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)

18
OUTPUT:

Please enter value for P: 5

Please enter value for Q:

The Value of P after swapping: 7

The Value of Q after swapping: 5

2 (b) Circulate ‘n’ values

ALGORITHM:

STEP 1: Read the values to be circulated in a list

STEP 2: Read the number of times of shifting in

n STEP 3: Using list slicing, perform rotation

STEP 4: Print (list[n:]+list[:n])

STEP 5: Stop

PROGRAM:

list=[10,20,30,40,50]

n=2 print(list[n:]

+list[:n])

OUTPUT:

[30, 40, 50, 10, 20]

19
2 (c) Distance between two points

ALGORITHM:

STEP 1: Read the values of x1,x2 and y1,y2


STEP 2: Import math module to calculate the square root
STEP 3: Compute the distance using the formula
STEP 4: Using the formula, find square root of ( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
STEP 5: Print the result
STEP 6: Stop

PROGRAM:

import math

p1 = [4, 0]

p2 = [6, 6]

distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2)

) print(distance)

OUTPUT:

6.324555320336759

RESULT:

Thus, the program for simple python statements and expressions were executed
and the output is verified.

20
Exp No :3

SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE LOOPS

3 (a) Number series

AIM:
To write a python program to evaluate 12+22+32+…+N2.

ALGORITHM:

Step 1: User must first enter the value and store it in a variable.

Step 2: The while loop is used and the last digit of the number is obtained by using the

modulus operator.

Step 3: The digit is added to another variable each time the loop is executed.

Step 4: Stop

PROGRAM

N=int(input(‘enter a number: ‘))


Sum=0
i=1
while i<=n:
sum=sum+i*i
i+=1
print(‘sum=’,sum)

OUTPUT:

Enter a number:

10 Sum=385

21
3 (b ) Number Pattern

ALGORITHM:

STEP 1: Read the number of rows to be printed

STEP 2: Using nested loop, print the spaces needed

STEP 3: Using binomial coefficient, print the values

STEP 4: Stop

PROGRAM:

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

for i in range(1, n+1):

for j in range(0, n-

i+1): print(' ', end='')

C=1

for j in range(1, i+1):

print(' ', C, sep='', end='')

C = C * (i - j) // j

print()

22
OUTPUT:

Enter the rows: 5

11

121

1331

14641

3 (c ) Print pyramid Patterns in python

ALGORITHM:

STEP 1: Read the row and column values

STEP 2: Using nested loops, print the required pattern

STEP 3: Stop

PROGRAM:
num_rows = int(input("Enter the number of rows"));

for i in range(0, num_rows):

for j in range(0, num_rows-i-1):

print(end=" ")

for j in range(0, i+1):

print("*", end=" ")

print()

23
OUTPUT:

Enter the number of rows 5

**

***

****

*****

RESULT:

Thus, the program using conditionals and loops has been executed and verified.

24
Exp No: 4
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS

a. Basic Operations (Insertion, Updating, deletion, accessing, List Comprehensions)

b. Implement linear search and binary search using list.

c. Matrix operations using Nested List.

d. Implement Merge, Bubble and Insertion sort

AIM:
To perform insertion, updating, deletion, accessing elements, and list
comprehensions. Implement linear search and binary search on a list. Add two matrices using
nested lists. Implement sorting algorithms using lists.
ALGORITHM:

1. Define the Problem Clearly state the objective, such as sorting a list,
searching an element, or performing matrix operations.
2. Input the Data Accept inputs from the user or define them directly in the code, like
lists, numbers, or matrices.
3. Initialize Variables Set up necessary variables, such as counters,
accumulators, or placeholders for results.
4. Process the Data Use conditionals, loops, or functions to perform
operations like traversing, searching, or sorting.
5. Store or Update Results Collect the computed values into variables, lists, or
matrices as required.
6. Output the Results Display the final results using print statements or return
values for further use.

25
4 a) Basic Operations

1. insert
# Initialize an empty list a
= []
# Adding 10 to end of list
a.append(10)
print("After append(10):", a) #
Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
# Adding multiple elements [15, 20, 25] at the end
a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)

2. update
a = [10, 20, 30, 40, 50]
# Change the second element a[1]
= 25
print(a)

3. delete
a = [10, 20, 30, 40, 50]
# Removes the first occurrence of 30
a.remove(30)
print("After remove(30):", a)
# Removes the element at index 1 (20)
popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

26
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)

4. List Function: list()

flowers = list(('Sunflower', 'Daisy', 'Tulip', 'Lavender', 'Rose'))


print(flowers)

5. accessing
a = ['apple', 'banana', 'cherry']
# Accessing the first item
print(a[0])
# Accessing the second item
print(a[1])
# Accessing the third item
print(a[2])

b) LINEAR SEARCH

def linearSearch(array, n, x):

for i in range(0, n):

if (array[i] == x):

return i

return -1

array = [24, 41, 31, 11, 9]

x = 11

n = len(array)

27
result = linearSearch(array, n, x)

if(result == -1):

print("Element not found")

else:

print("Element is Present at Index: ", result)

OUTPUT

Element is Present at Index: 3

BINARY SEARCH

def binarySearch(array, x, low, high):

while low <= high:

mid = low + (high - low)//2

if array[mid] == x:

return mid

elif array[mid] <

x:

low = mid + 1

else:

high = mid - 1

return -1

array = [2, 4, 5, 7, 14, 17, 19, 22]

x = 22

28
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:

29
print(str(result))

else:

print("Not found")

Output

c) MATRIX OPERATION USING NESTED LIST

Row = int(input("Enter the number of rows:"))

Column = int(input("Enter the number of

columns:")) # Initialize matrix

matrix = []

print("Enter the entries row wise:")

# For user input

# A for loop for row entries

for row in range(Row):

a = []

# A for loop for column

entries for column in

range(Column):

a.append(int(input()))

matrix.append(a)

30
# For printing the

matrix for row in

range(Row):

for column in range(Column): print(matrix[row]

[column], end=" ")

print()

OUTPUT

Enter the number of rows:2


Enter the number of columns:2
Enter the entries row wise:
5
6
7
8

56
78

d) 1. MERGE SORT

def merge(arr, l, m, r):

n1 = m - l +

1 n2 = r - m

L = [0] * n1

R = [0] * n2

for i in range(n1):

31
L[i] = arr[l + i]

32
for j in range(n2):

R[j] = arr[m + 1 + j]

i=0

j=0

k=l

while i < n1 and j < n2:

if L[i] <= R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

j += 1

k += 1

while i < n1:

arr[k] = L[i]

i += 1

k += 1

while j < n2:

arr[k] = R[j]

j += 1

k += 1

33
def merge_sort(arr, l, r):

if l < r:

m = l + (r - l) // 2

merge_sort(arr, l, m)

merge_sort(arr, m + 1, r)

merge(arr, l, m, r)

def print_array(arr):

for i in arr:

print(i, end=" ")

print()

if name == " main ":

arr = [12, 11, 13, 5, 6, 7]

arr_size = len(arr)

print("Given array is")

print_array(arr)

merge_sort(arr, 0, arr_size -

1) print("\nSorted array is")

print_array(arr)

34
OUTPUT

Given array is

12 11 13 5 6 7
Sorted array
is 5 6 7 11 12
13
d. 2. INSERTION SORT
def insertion_sort(arr):

for i in range(1,

len(arr)): key =

arr[i]

j=i-1

while j >= 0 and arr[j] > key:

arr[j + 1] = arr[j]

j=j-1

arr[j + 1] = key

def print_array(arr):

for i in arr:

print(i, end=" ")

print()

if name == " main ":

arr = [12, 11, 13, 5, 6]

35
n = len(arr)

print("Given array is")

print_array(arr)

36
insertion_sort(arr) print("\

nSorted array is")

print_array(arr)

OUTPUT

Given array
is 12 11 13 5
6
Sorted array
is 5 6 11 12
13

d.3.BUBBLE SORT
def bubble_sort(arr):

# Outer loop to iterate through the list n times

for n in range(len(arr) - 1, 0, -1):

# Inner loop to compare adjacent elements

for i in range(n):

if arr[i] > arr[i + 1]:

# Swap elements if they are in the wrong order

swapped = True

arr[i], arr[i + 1] = arr[i + 1],

arr[i] # Sample list to be sorted

arr = [39, 12, 18, 85, 72, 10, 2, 18]

37
print("Unsorted list is:")

print(arr)

bubble_sort(arr)

print("Sorted list is:")

print(arr)

OUTPUT

Unsorted list is:


[39, 12, 18, 85, 72, 10, 2, 18]
Sorted list is:
[2, 10, 12, 18, 18, 39, 72, 85]

RESULT:

The results of the programs are as follows: Basic list operations show successful
insertion, updating, deletion, and accessing with comprehensions producing squares. Linear

38
search finds an index, and binary search works after sorting. Matrix addition gives element-wise
sums. Bubble, insertion, and merge sort all produce a sorted list efficiently.

39
Exp No: 5
CREATE A TUPLE AND PERFORM ITS OPERATIONS FOR THE FOLLOWING:

a. Basic Operations (Insertion, Updating, deletion, accessing)

b. Items present in a library

c. Components of a car

d. Materials required for construction of a laboratory

AIM:
To perform insertion, updating, deletion, and accessing elements in a tuple, library operations
and material construction.
ALGORITHM:

Define the Tuple


Create a tuple containing the required data, such as numbers, library items, car
components, or materials for laboratory construction.
Access Elements
Access specific elements from the tuple using indexing to retrieve and display
values.
Modify the Tuple (if required)
Since tuples are immutable, convert the tuple to a list for insertion, updating, or
deletion of elements.
Perform Operations
Apply specific operations like adding new items, modifying existing ones, or
deleting items, then convert the list back to a tuple.
Output the Results
Display the modified tuple or the results of any operations performed.

40
a) Creating a Tuple

# Creating an empty
Tuple Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple
with # the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

OUTPUT
Initial empty Tuple:
()
Tuple with the use of
String: ('Geeks', 'For')
Tuple using List:

(1, 2, 4, 5, 6)
Tuple with the use of
function: ('G', 'e', 'e', 'k', 's')

41
Inserting Tuple

# Python3 code to demonstrate working of

# Adding Tuple to List and vice - versa

# Using += operator (list +

tuple) # initializing list

test_list = [5, 6, 7]

# printing original list

print("The original list is : " +

str(test_list)) # initializing tuple

test_tup = (9, 10)

# Adding Tuple to List and vice -

versa # Using += operator (list + tuple)

test_list += test_tup

# printing result

print("The container after addition : " + str(test_list))

OUTPUT

The original list is : [5, 6, 7]


The container after addition : [5, 6, 7, 9, 10]

42
Accessing Tuple

# Accessing

Tuple # with

Indexing

Tuple1 = tuple("Geeks") print("\

nFirst element of Tuple: ")

print(Tuple1[0])

# Tuple unpacking

Tuple1 = ("Geeks", "For", "Geeks")

# This line unpack

# values of Tuple1

a, b, c = Tuple1

print("\nValues after unpacking: ")

print(a)

print(b)

print(c)

OUTPUT

First element of
Tuple: G
Values after unpacking:
Geeks
For

Geeks

43
UPDATING TUPLES

tu = ('a', 'b', 'c')


tu[0] = 'p' #will generate error
print(tu)

OUTPUT

ERROR!

Traceback (most recent call last):

File "<main.py>", line 2, in <module>

TypeError: 'tuple' object does not support item assignment

DELETING A TUPLE

tu = ('a', 'b',
'c') del tu[0]
print(tu)

OUTPUT

TypeError: 'tuple' object doesn't support item deletion

b) Display the Book details using a list

my_book=[]

ch='y'

while(ch=='y'):

print('''1. Add New Book

2. Display Books''')

44
choice=int(input("Enter choice: "))

if(choice==1):

book=input("Enter the name of the book:")

my_book.append(book)

elif(choice==2):

for i in my_book:

print(i)

else:

print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

OUTPUT:

1. Add New Book

2. Display Books

Enter choice: 1

Enter the name of the book:Python programming

Do you want to continue...?y

c). Automobile Components using Lists

components=['RADIATOR','ACCOMPRESSOR','BATTERY','ALTERNATOR','AXLE','BRA

KES','SHOCK ABSORBERS','TRANSMISSION','FUEL TANK']

45
components1=['CATALYTIC CONVERTER','MUFFLER','TAILPIPE']

ch='y'

while(ch=='y'):

print('''

1. Display Main Components

2. Display All Components

3. Total Components

4. Components in Alphabetical

Order ''') choice=int(input("Enter

choice: ")) if(choice==1):

print("The Main components

are:") print(components)

elif(choice==2):

print("The components are:")

print(components+components1)

elif(choice==3):

print("The components are:")

print("Main Components:",len(components))

print("Other Components:",len(components1))

elif(choice==4):

46
print("The components in alphabetical order

are:") components.sort()

print("Main Components:",components)

print("Sorted order")

else:

print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

OUTPUT:

1. Display Main Components

2. Display All Components

3. Total Components

4. Components in Alphabetical

Order Enter choice: 4

The components in alphabetical order are:

Main Components: ['AC COMPRESSOR', 'ALTERNATOR', 'AXLE', 'BATTERY',

'BRAKES', 'FUEL TANK', 'RADIATOR', 'SHOCK ABSORBERS', 'TRANSMISSION']

Sorted order

Do you want to continue...?

d). Materials of Construction using Tuple

types=('Artificial Materials','Natural Materials')

47
material=('Cement','Aggregates','Stones and Rocks','Mud and Clay',

'Concrete','Bricks','Glass','Plastic','Structural Steel',

'Foam','Fabric','Thatch','Timber and Wood','Tiles (Ceramics)',

'Electrical Items')

ch='y'

while(ch=='y'):

print('''1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at random''')

choice=int(input("Enter choice:

")) if(choice==1):

print(material)

elif(choice==2):

print(types)

elif(choice==3):

print(material[::-1])

elif(choice==4):

print(len(material))

elif(choice==5):

48
print(material[5])

else:

print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

OUTPUT:

1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at

random Enter choice: 4

15

Do you want to continue...?y

1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at

random Enter choice: 5

Bricks

49
Do you want to continue...?

RESULT:

The tuple operations result in successful creation, modification, and retrieval of elements.
Library items include books, magazines, and journals. Car components include engine and
wheels. Laboratory materials include cement and glass. Basic operations like insertion, updating,
and deletion are achieved by converting tuples to lists and back to tuples.

50
Exp No. 6
IMPLEMENTING BASIC OPERATIONS ON SETS

a. Membership

b. Operations

c. Modifications

AIM:

To perform basic operations on sets including membership checks, set operations (union,
intersection, difference, and symmetric difference), and modifications (add, remove, update, and
clear).
ALGORITHM:

1. Define a Set ,Create a set with initial elements using curly braces {} or the set() constructor.

2. Membership Check Input the element to be checked. Use the in keyword to verify membership: If
the element exists, output True. Otherwise, output False.

3. Perform Set Operations Define two sets. Compute:

Union using | or .union().

Intersection using & or .intersection().

Difference using - or .difference().

Symmetric Difference using ^ or .symmetric_difference().

4. Modify the Set

Perform the following operations:

51
Add an element using .add().

Update with multiple elements using .update().

Remove a specific element using .remove() or .discard().

Pop an arbitrary element using .pop().

Clear the set using .clear().

5. Display Results

Print the updated sets and results of the operations.

6. End

a. Membership

1. Python IN Operator

# initialized some sequences

set1 = {1, 2, 3, 4, 5}

# using membership 'in' operator

print(6 in set1)

OUTPUT

False
2. Python NOT IN
Operator # initialized
some sequences

set1 = {1, 2, 3, 4, 5}

52
# using membership 'not in' operator

# checking an integer in aset

print(6 not in set1)

OUTPUT

True

Operations

Set Union

>>> first_set = {1, 2, 3}


>>> second_set = {3, 4, 5}
>>> first_set.union(second_set)
OUTPUT

{1, 2, 3, 4, 5}

Set Intersection

>>> first_set = {1, 2, 3, 4, 5, 6}


>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.intersection(second_set)
OUTPUT

{4, 5, 6}

3. Set Difference

>>> first_set = {1, 2, 3, 4, 5, 6}


>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.difference(second_set)

53
OUTPUT

{1, 2, 3}

3. Set Symmetric Difference

>>> first_set = {1, 2, 3, 4, 5, 6}


>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.symmetric_difference(second_set)
OUTPUT

{1, 2, 3, 7, 8, 9}

b. Modifications

my_set = {1,

2, 3, 4} # Add

an element

my_set.add(5)

print("After add:", my_set) # {1, 2, 3, 4, 5}

# Update with multiple elements

my_set.update([6, 7, 8])

print("After update:", my_set) # {1, 2, 3, 4, 5, 6, 7, 8}

# Remove an element

my_set.remove(3)

print("After remove:", my_set) # {1, 2, 4, 5, 6, 7, 8}

# Discard an element

54
my_set.discard(10) # No error even though 10 is not in the set

print("After discard:", my_set) # {1, 2, 4, 5, 6, 7, 8}

# Pop an arbitrary element

popped_element = my_set.pop()

print("Popped element:", popped_element)

print("After pop:", my_set)

# Clear the

set

my_set.clear()

print("After clear:", my_set) # set()

OUTPUT

After add: {1, 2, 3, 4, 5}

After update: {1, 2, 3, 4, 5, 6, 7, 8}

After remove: {1, 2, 4, 5, 6, 7, 8}

After discard: {1, 2, 4, 5, 6, 7, 8}

Popped element: 1

After pop: {2, 4, 5, 6, 7,

8} After clear: set()

RESULT:

The program demonstrates basic set operations in Python, including membership checks,
set operations like union, intersection, difference, and symmetric difference, and modifications
using methods such as .add(), .update(), .remove(), .discard(), and .pop(). It efficiently verifies
membership, manipulates elements, and clears the set using .clear(), producing expected results
55
and showcasing the flexibility of Python sets.

56
Ex no: 7. Operations of Dictionaries

a. Python program to create a dictionary with integer keys, and print the
keys, values &amp;

key-value pairs

b. Python program to randomize (shuffle) values of dictionary

c. Python program to create a dictionary with integer keys, and print the keys, values
&amp;

key-value pairs

Aim:

To demonstrate the operations of dictionaries in Python by writing programs to: Create a


dictionary with integer keys and print its keys, values, and key-value pairs. Shuffle the values of
a dictionary randomly.

Algorithm:

Step 1: Start the program.

Step 2: Create a dictionary with integer keys and assign values to them.

Step 3: Use the .keys() method to retrieve and print all keys.

Step 4: Use the .values() method to retrieve and print all values.

Step 5: Use a loop to iterate over the dictionary and print the key-value pairs.

Step 6: End the program.

57
Program

# Python program to create a dictionary

# With integer keys

# Creating the dictionary

dict_a = {1 : "India", 2 : "USA", 3 : "UK", 4 :

"Canada"} # Printing the dictionary

print ("Dictionary \'dict_a\' is...")

print(dict_a)

# Printing the keys only

print ("Dictionary \'dict_a\' keys...")

for x in dict_a:

print(x)

# Printing the values only

print ("Dictionary \'dict_a\' values...")

for x in dict_a.values():

print(x)

# Printing the keys & values

print ("Dictionary \'dict_a\' keys & values...")

for x, y in dict_a.items():

print (x, ':', y)

58
OUTPUT:

Dictionary 'dict_a' is...


{1: 'India', 2: 'USA', 3: 'UK', 4: 'Canada'}

Dictionary 'dict_a' keys...

Dictionary 'dict_a' values...

India

USA

UK

Canada

Dictionary 'dict_a' keys & values...

1 : India

2 : USA

3 : UK

4 : Canada

59
a. Python program to randomize (shuffle) values of dictionary

Step 1: Start the program.

Step 2: Import the random module to enable shuffling. Step

3: Create a dictionary with key-value pairs.

Step 4: Extract the values of the dictionary using .values() and convert them into a list.

Step 5: Use the shuffle method from the random module to randomize the list of

values.

Step 6: Reassign the shuffled values back to the original dictionary, ensuring the keys remain the
same.

Step 7: Print the updated dictionary to show the randomized values.

Step 8: End the program.

Program

# Python program to shuffle dictionary Values... #

Importing shuffle method from random

from random import shuffle #

Initialising dictionary

myDict = {'Scala': 2, 'Javascript': 5, 'Python': 8, 'C++': 1, 'Java': 4} #

Shuffling Values...

valList = list(myDict.values())

shuffle(valList)

mappedPairs = (zip(myDict, valList))

shuffledDict = dict(mappedPairs)
60
# Printing the dictionaries...

61
print("Initial dictionary = ", end = " ")

print(myDict)

print("Shuffled dictionary = ", end = " ")

print(shuffledDict)

OUTPUT RUN 1:

Initial dictionary = {'Java': 4, 'Scala': 2, 'Python': 8, 'C++': 1, 'Javascript': 5}

Shuffled dictionary = {'Javascript': 4, 'Scala': 1, 'Java': 2, 'C++': 8, 'Python': 5}

RUN 2:

Initial dictionary = {'C++': 1, 'Scala': 2, 'Javascript': 5, 'Java': 4, 'Python': 8}

Shuffled dictionary = {'C++': 8, 'Scala': 1, 'Javascript': 2, 'Java': 5, 'Python': 4}

RUN 3:

Initial dictionary = {'C++': 1, 'Javascript': 5, 'Scala': 2, 'Java': 4, 'Python': 8}

Shuffled dictionary = {'C++': 8, 'Javascript': 4, 'Scala': 2, 'Python': 1, 'Java': 5}

Result:

Part (a): The program successfully creates a dictionary, prints its keys, values, and key-value
pairs.

Part (b): The program randomizes the values of a dictionary while keeping the keys intact. The
shuffled dictionary is displayed.

62
Ex no: 8. Implementing programs using Functions.

a. Factorial

b. largest number in a list

c. Area of shape

a. Factoria

l Aim:

To write a python program for implementing a factorial of a given number using Recursion.

Algorithm:

Step 1: Start

Step 2: Read a number

Step 3: Pass the number as an argument to a recursive factorial function.

Step 4: Define the base condition as the number to be lesser than or equal to 1 and return 1 if it
is.

Step 5: Otherwise call the function recursively with the number minus 1 multiplied by the
number itself.

Step 6: Print the


result.

Step 7: Stop

Program

def factorial(n):

63
if n == 0:

return 1

else:

return n * factorial(n-1)

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

print(f"The factorial of {num} is {factorial(num)}")

OUTPUT

Enter a number: 5

The factorial of 5 is 120

b. largest number in

a list Aim :

To write a program to find the largest number in a list using python.

Algorithm :

Step 1 : Start

Step 2 : Read number of elements to be store in a

list Step 3 : Initialize an empty list lst = [].

Step 4 : Read each number in your python program using a for loop.

Step 5 : In the for loop append each number to the list.

Step 6 : Define a custom function, which is an accepted number list and used to

find the largest number from list.

64
Step 7 : Call this custom function and store the function result.

Step 8 : Print the result.

Step 9 : Stop

Program

def find_largest(numbers):

return max(numbers)

numbers = [int(x) for x in input("Enter numbers separated by space: ").split()]

print(f"The largest number in the list is {find_largest(numbers)}")

OUTPUT

Enter numbers separated by space: 5 9 4 3 2 7 1

The largest number in the list is 9

Area of shape

Aim :

To write a program to find the area of different shapes using python.

Algorithm :

Step 1 : Start.

Step 2 : Call the appropriate shapes and get the inputs.

Step 3 : Compute the formula as the shapes.

Step 4 : Return the area

Step 5 : Print the area.


65
Step 6 : Stop

Circle

import math

def area_circle(radius):

return math.pi * radius ** 2

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

print(f"The area of the circle is

{area_circle(radius)}") OUTPUT

Enter the radius of the circle: 3

The area of the circle is 28.274333882308138

Rectangle
def area_rectangle(length, width):

return length * width

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 {area_rectangle(length, width)}")

OUTPUT

Enter the length of the rectangle: 3

Enter the width of the rectangle: 5

The area of the rectangle is 15.0

Triangle
def area_triangle(base, height):

return 0.5 * base * height


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

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

print(f"The area of the triangle is {area_triangle(base, height)}")

OUTPUT

Enter the base of the triangle: 3

Enter the height of the triangle: 4

The area of the triangle is 6.0

Result:

The functions implemented for each program performed their tasks accurately. The results were
validated by testing multiple inputs, and the outputs were as expected. Thus the program was
implemented and executed successfully.

67
Ex no: 9. Implementing programs using Strings

a. Reverse

b. Palindrome

c. Character count

d. Replacing characters

Aim:

To implement Python programs for various string manipulations:

Reverse a string.

Check if a string is a palindrome.

Count the occurrences of a specific character in a string.

Replace characters in a string.

Reverse a String Algorithm:

Step 1: Start the program.

Step 2: Take a string input from the user.

Step 3: Reverse the string using slicing ([::-1]) or a loop.

Step 4: Print the reversed string.

Step 5: End the program.

68
Program
def reverse_string(s):

return s[::-1]

# Example usage

input_string = "hello"

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

OUTPUT

Reversed string: olleh

a. Palindrome

Step 1: Start the program.

Step 2: Take a string input from the user.

Step 3: Remove case differences by converting the string to lowercase.

Step 4: Compare the string with its reversed version.

Step 5: Print whether the string is a palindrome.

Step 6: End the program.

Program

def is_palindrome(s):

69
return s == s[::-1]

# Example usage

input_string = "madam"

if is_palindrome(input_string):

print(f"'{input_string}' is a palindrome.")

else:

print(f"'{input_string}' is not a palindrome.")

OUTPUT

'madam' is a palindrome.

b. Character count

Step 1: Start the program.

Step 2: Take a string input and a character to search for from the user.

Step 3: Use the .count() method to count occurrences of the character.

Step 4: Print the count.

Step 5: End the program.

Program

def character_count(s):

count = {}

for char in s:

70
if char in count:

count[char] +=

else:

count[char] = 1

return count

# Example usage

input_string = "hello"

print("Character count:", character_count(input_string))

OUTPUT

Character count: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

c. Replacing characters

Step 1: Start the program.

Step 2: Take a string input from the user.

Step 3: Take the character to replace and the new character as inputs.

Step 4: Use the .replace() method to replace the characters.

Step 5: Print the updated

string. Step 6: End the

program.

71
Program

def replace_characters(s, old, new):

return s.replace(old, new)

# Example usage

input_str = "hello world"

print("Replaced String:", replace_characters(input_str, 'o', 'a'))

OUTPUT

Replaced String: hella warld

Result

The programs for string manipulation successfully reversed strings, identified palindromes,
counted specific character occurrences, and replaced characters. Each function provided accurate
and validated results. Examples include reversing "hello" to "olleh", identifying "madam" as a
palindrome, counting 2 occurrences of in "programming", and replacing with in "apple".
'g' 'p' 'b'

72
Ex no: 10. Implementing programs using written modules and Python Standard
Libraries (pandas, numpy, matplotlib, scipy)

10(a) Simple Program using

numpy AIM:

To write a python program to plot a simple python graph for a straight line.

ALGORITHM:

1. Start the Program

2. Import the modules numpy, pyplot

3. Store the set of values in x, equation in y

4. Assign title, axis label for the graph

5. Show the graph

6. Stop

PROGRAM:

import numpy as np

from matplotlib import pyplot as

plt x = np.arange(1,11)

y=2*x+7

plt.title("Matplotlib demo")

plt.xlabel("x axis caption")

plt.ylabel("y axis caption")


73
plt.plot(x,y) plt.show()

10. (b) Program using

pandas AIM:

To create data frames using pandas in python.

ALGORITHM:

1. Start the Program.

2. Import numpy and pandas

3. Create a dictionary with student name, marks of three subjects

4. Convert the dictionary to a data frame

5. Print the data frame

6. Stop

PROGRAM:

import numpy as np

import pandas as pd

74
mydictionary =

{'names': ['Somu',

'Kiku', 'Amol',

'Lini'], 'physics':

[68, 74, 77, 78],

'chemistry': [84, 56, 73, 69],

'algebra': [78, 88, 82, 87]}

#create dataframe using dictionary

df_marks = pd.DataFrame(mydictionary)

print(df_marks)

75
10(c) Using Scipy - Univariate

Interpolation AIM:

To implement a python Program to plot an univariate interpolation.

ALGORITHM:

1. Start

2. Import interpolate , pyplot

3. Using x, y values arrange the graph area

4. Using pyplot , print the graph

5. Stop
PROGRAM:

import matplotlib.pyplot as plt

from scipy import interpolate

x = np.arange(5, 20)

y = np.exp(x/3.0)

f = interpolate.interp1d(x, y)

x1 = np.arange(6, 12)

y1 = f(x1) # use interpolation function returned by `interp1d`

plt.plot(x, y, 'o', x1, y1, '--')

plt.show(

76
Result:

Implementing programs using written modules and Python libraries like Pandas, NumPy,
Matplotlib, and SciPy involves combining modular programming with powerful data
manipulation, numerical computation, and visualization tools were implemented in python.

77
E.NO:11 implementing real-time/technical applications using file handling.

A. Python program to copy the content of one file

into another file Aim:

To write a program to copy the content of one file into another file

Algorithm:

Step 1: Start

Step 2: Open one file called test.txt in read mode.

Step 3: Open another file out.txt in write mode.

Step 4: Read each line from the input file and write it into the output file.

Step 5: Stop.

Program:

print("Enter the Name of Source File: ")

sourcefile = input()

print("Enter the Name of Target File: ")

targetfile = input()

fileHandle = open(sourcefile, "r")

texts = fileHandle.readlines()

fileHandle.close()

fileHandle = open(targetfile, "w")

78
for s in texts:

fileHandle.write(s)

fileHandle.close()

print("File Copied Successfully!")

Output:

Enter the Name of Source File: in.txt

Enter the Name of Target File:

out.txt File Copied Successfully

B. Python Program to Count the Number of Words in

a Text File Aim:

To write a Python Program to Count the Number of Words in a Text File

Algorithm:

Step 1: Start

Step 2: Open file “book.txt” in read mode and store contents of file in file object say

fin Step 3: Read each line from the file using read() function

Step 4: Split the line to form a list of words using split() function and store it in variable

Step 5: Intitially Set the value of count_words variable to zero in which we will store

the Calculated result.

Step 6: Use for loop to read list of word stored in variable say

l. Step 7: Find the length of words in the list and print it.

79
Step 8: Close the file using close()

function.Program: Step 9: Stop

Program:

fin = open("book.txt","r")

str = fin.read()

l = str.split()

count_words = 0

for i in l:

count_words = count_words + 1

print(count_words)

fin.close()

Output:

25

80
C. Python Program to find longest Word in Text File

Aim:

To write a Python Program to find longest Word in a Text File

Algorithm:

Step 1: Start

Step 2: Open text file say ‘name.txt’ in read mode using open function

Step 3: Pass file name and access mode to open function

Step 4: Read the whole content of text file using read function and store it in another

variable say ‘str’

Step 5: Use split function on str object and store words in variable say ‘words’

Step 6: Find maximum word from words using len method

Step 7: Iterate through word by word using for loop

Step 8: Use if loop within for loop to check the maximum length of word

Step 9: Store maximum length of word in variable say ‘longest_word’

Step 10: Display longst_word using print function

Step 11: Stop

Program:

fin = open("name.txt","r")

str = fin.read()

words = str.split()

81
max_len = len(max(words, key=len))

for word in words:

if len(word)==max_len:

longest_word =word

print(longest_word)

Output:

Encyclopedia

Result:

Thus the program for real-time/technical applications using File handling was

Implemented and executed successfully.

82
Ex No: 12 Implementing real-time / technical applications using Exception handling

AIM:

To implement python program for real-time / technical applications using Exception

Handling.

ALGORITHM:

STEP1: Get the input for n, d and c.

STEP2: In the try block, calculate q=n/(d-c).

STEP3: If the denominator is non-zero, then the quotient gets printed.

STEP4: Otherwise, the exception Zero Division Error is executed.

PROGRAM:

n=int(input("Enter the value of n:"))

d=int(input("Enter the value of d:"))

c=int(input("Enter the value of c:"))

try:

q=n/(d-c)

print("Quotient:",q)

except ZeroDivisionError:

print("Division by Zero!")

83
OUTPUT:
Enter the value of n:

10 Enter the value of

d: 5 Enter the value of

c: 5 Division by Zero!

84
12 a) VOTER’S AGE VALIDITY

ALGORITHM:

STEP1: Get the age from the user.

STEP2: In the if block, check if the age is greater than 18, then print “Eligible to vote”.

STEP3: Otherwise, print “Not eligible to vote”

STEP4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:

def main():

try:

age=int(input("Enter your age"))

if age>18:

print("Eligible to vote")

else:

print("Not eligible to vote")

except:

print("age must be a valid

number") main()

OUTPUT 1:

Enter your age 24

Eligible to vote

OUTPUT 2:
85
Enter your age 14

Not eligible to vote

12(a). STUDENT MARK RANGE VALIDATION

ALGORITHM:

STEP1: Get the number between the range(1 - 100)

STEP2: In the if block, check whether the number is between 1 to 100.

STEP3: Otherwise, print “Above 100, wrong”

STEP4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:

def input_number(min,max):

try:

while True:

n=int(input("Please enter a number between {} and {} :".format(min,max)))

n=int(n)

if(min<=n<=max):

print(n)

break

else:

print("Above 100, wrong")


86
break

except:

print("mark must be a valid

number") input_number(1,100)

OUTPUT 1:

Please enter a number between 1 and 100 :4

OUTPUT 2:

Please enter a number between 1 and 100 :156

Above 100, wrong

OUTPUT 3:

Please enter a number between 1 and 100 : ab

mark must be a valid number

RESULT:

Thus the program for real-time / technical applications using Exception handling was

Implemented and executed successfully.

87
Ex no :13. Python programs using Time and Calendar related functions

a. Print the current time using time module.

b. Display the calendar of given month of the year

using calendar Aim:

The aim of this program is to demonstrate the use of time and calendar modules in Python for
performing tasks related to date and time. Specifically, the program will:

1. Print the current time in a readable format using the time module.
2. Display the calendar of a specified month and year using the calendar
module.

Algorithm:

Import Required Modules:


o Import the time and calendar modules.
Print Current Time:
o Use time.localtime() to get the current time structure.
o Format the time using time.strftime() to display it in a human-readable
format.
Display Calendar:
o Accept inputs for the year and month.
o Use calendar.month() to generate the month's calendar.
o Print the calendar.

Print the current time using time module.

Today’s date and time

from datetime import date

today = date.today()

88
print("Today's date:", today)

89
Output:

Today's date: 2022-12-27

Current date in different formats

from datetime import date

today = date.today()

# dd/mm/YY

d1 = today.strftime("%d/%m/%Y")

print("d1 =", d1)

# Textual month, day and year

d2 = today.strftime("%B %d, %Y")

print("d2 =", d2)

# mm/dd/y

d3 =

today.strftime("%m/%d/%y")

print("d3 =", d3)

# Month abbreviation, day and

year d4 = today.strftime("%b-%d-

%Y") print("d4 =", d4)

90
Output:

d1 = 27/12/2022
d2 = December 27,
2022 d3 = 12/27/22
d4 = Dec-27-2022

a. Display the calendar of given month of the year using calendar

# Program to display calendar of the given month and

year # importing calendar module

import calendar

yy = 2014 #

year

mm = 11 # month

# To take month and year input from the

user # yy = int(input("Enter year: "))

# mm = int(input("Enter month:

")) # display the calendar

print(calendar.month(yy, mm))

91
November 2014
Mo Tu We Th Fr Sa Su
12
34 5 67 89
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Result:

1. The current time is printed in the format YYYY-MM-DD HH:MM:SS,


allowing the user to view the exact time the program is executed.
2. After entering a year and month, the program displays a neatly
formatted calendar of the specified month using the calendar
module. This demonstrates the utility of Python's built-in libraries
for time and calendar management.

You might also like