Mc4167 Python Programming Laboratory Manual
Mc4167 Python Programming Laboratory Manual
DEPARTMENT
OF
MASTER OF COMPUTER APPLICATION
LAB MANUAL
(REGULATION - 2024)
FIRST SEMSTER
Prepared By
MR. [Link] [Link].,[Link].,(Ph.D)
Assistant Professor
VISION OF THE DEPARTMENT
To educate students with conceptual knowledge and technical skills in the field of Computer
Applications with moral and ethical values to achieve excellence in academic, industry, and
research- centric environments.
1. To bring the most brilliant students and faculty together to understand the strengths and limits of
computation, invent next-generation computing systems, and create innovative solutions to real-
world problems.
3. Deliver knowledge among students through novel pedagogical methods in the varied areas of
computer sciences with thrust on applications so as to enable students to undertake research.
4. To facilitate students to nurture skills to practice their professions competently to meet the ever-
changing needs of society.
ii
INDEX
E. NO EXPERIMENT NAME [Link].
A PEO,PO 1
B SYLLABUS 3
E MODE OF ASSESSMENT 5
LIST OF EXPERIMENTS:
1. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
2. Scientific problems using Conditionals and Iterative loops.
3. Linear search and Binary search
4. Selection sort, Insertion sort
5. Merge sort, Quick Sort
6. Implementing applications using Lists, Tuples.
7. Implementing applications using Sets, Dictionaries.
8. Implementing programs using Functions.
9. Implementing programs using Strings.
10. Implementing programs using written modules and Python Standard Libraries (pandas,numpy,
Matplotlib, scipy)
11. Implementing real-time/technical applications using File handling.
Total: 60 Periods
4
LIST OF EQUIPMENTS FOR A BATCH OF 30 STUDENTS
HARDWARE/SOFTWARE REQUIREMENTS
COURSE OUTCOMES
CO- PO MATRIX
5
EVALUATION PROCEDURE FOR EACH EXPERIMENT
2. Observation 20
5. Viva 20
Total 100
2. Record 10
3. Model Test 20
Total 60
6
[Link]
PYTHON PROGRAMMING USING SIMPLE STATEMENTS AND EXPRESSIONS
[Link]:1a
AIM:
To exchange the given values of two variables using python.
PRE LAB DISCUSSION:
An expression is a code construct that is evaluated to a value. A code construct is a piece of code.
Following are some common expressions:
An object or a declared variable, such as: 3, Hi, x, [1, 2, 3].
A computation using operators, such as 3 + 5, x < y < z.
A function call, such as len("hello"), [Link](3, 2).
Functions defined inside types are called methods. A method call is an expression.
For example: "hello".upper(), [1, 2, 3].pop().
Simple statements
assignment statement name = expression
return statement: return expression
import statement: import module_name
Compound Statements
A compound statement contains multiple statements that usually span multiple lines.
Compound statements are used to control program flow or create new data types like functions
and classes.
ALGORITHM:
PROGRAM:
print("Swapping using temporary variable")
a = int(input("a = "))
b = int(input("b = "))
print("Before Swapping")
print("a = ", a)
print("b = ", b)
c=a
a=b
b=c
print("After Swapping")
print("a = ", a)
print("b = ", b)
7
OUTPUT:
a = 10
b = 20
Before Swapping
a = 10
b = 20
After Swapping
a = 20
b = 10
RESULT
Thus the program to exchange the given values of two variables using python has been executed
successfully.
8
[Link].1b.
CIRCULATE THE VALUES OF N VARIABLES
Aim:
Algorithm:
Step 1: Start the program.
Step 2: Get one integer input no_of_terms from the user using the input() function.
Step 3: Read the value of no_of_terms.
Step 4: Create a list as list1.
Step 5: Validate the range of no_of_terms.
Step 6: Then, get one integer input ele from the user using input() function.
Step 7: Add a single item to the existing list using the append method.
Step 8: Print the circulative values.
Step 9: Stop the program.
PROGRAM:
9
OUTPUT:
Result:
Thus the program has been executed successfully circulate the given values of n variables using
python.
10
[Link]:1c
CALCULATE DISTANCE BETWEEN TWO POINTS
AIM:
To calculate distance between two points using python
ALGORITHM:
11
OUTPUT
RESULT
Thus the program to calculate distance between two points using python has been executed successfully
12
[Link] SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE LOOPS
AIM :
To write a Python Program for scientific problems using conditionals and iterative loops
if-else Statement
x=4
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
if-elif-else Statement
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is exactly 10")
else:
print("x is less than 10")
2. Iterative Loops
for loops and while loops
for Loop
case:1
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
13
print(fruit)
case:2
for i in range(5):
print(i)
while Loop
count = 0
while count < 5:
print(count)
count += 1
# Increment the count to eventually end the loop
Using if Inside a for Loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
14
[Link]:2a FIBONACCI SERIES
AIM:
Fibonacci Sequence is a series of numbers starting with 0 and 1 in which each number, is generated by
adding the two preceding numbers. It is a special sequence of numbers that starts from 0 and 1 and then the next
terms are the sum of the previous terms and they go up to infinite terms.
ALGORITHM:
Step1:Start
Step2:Get the number of terms
Step3: Check if the number of terms is valid
Step4:If there is only one term, return n1
Step5:If it not generate the fibonacci sequence upto n terms
Step6:End
PROGRAM:
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
15
OUTPUT:
Fibonacci sequence:
RESULT:
Thus the program is executed to find the Fibonacci series of a given number and the output is obtained.
16
[Link]:2b AMSTRONG NUMBER
AIM :
To write a Python program to find the Armstrong number.
PRELAB DISCUSSION:
Given a number x, determine whether the given number is Armstrong number or not. A positive integer
of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
ALGORITHM:
Step1:Start
Step2:Define Function to calculate x raised to the power y
Step3: Calculate order of the number
Step4:Then add the number with the sum
Step5:Define the function isArmstrong() to check the given is armstrong number or not.
Step6:If it the digit is a armstrong number
Step6:If it is not the digit is not a Armstrong number.
PROGRAM/SOURCE CODE:
def power(x, y):
if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)
return x * power(x, y // 2) * power(x, y // 2)
def order(x):
n=0
while (x != 0):
n=n+1
x = x // 10
return n
def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0
16
while (temp != 0):
r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10
return (sum1 == x)
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))
OUTPUT:
True
False
RESULT:
Thus the program is executed to find the given number is Armstrong number or not and the output is
obtained.
17
[Link]:2c PALINDROME
AIM:
Write a Python program to reverse the digits of a given number and add them to the
original. Repeat this procedure if the sum is not a palindrome.
PRELAB DISCUSSION:
A palindrome is a word, number, or other sequence of characters which reads the same
backward as forward, such as madam or race car.
ALGORITHM:
Step1:Start
Step4:If the end of the string Matches with the first string then given digit is a palindrome
Step5:End
PROGRAM:
def rev_number(n):
s=0
while True:
k = str(n)
if k == k[::-1]:
break
else:
m = int(k[::-1])
n += m
s += 1
return n
rev=int(input(“enter num:”))
print(rev_number(rev))
18
OUTPUT:
RESULT:
Thus the program is executed to find the palindrome of a given number and the output is obtained
19
[Link]:3a LINEAR SEARCH
AIM :
To write a python Program to perform linear search
PRELAB DISCUSSION:
Linear search is a sequential searching algorithm where we start from one end and check every
element of the list until the desired element is found. It is the simplest searching algorithm.
ALGORITHM:
Step 1: Start.
Step 2: Read the number of element in the list.
Step 3: Read the number until loop n -1.
Step 4: Then Append the all element in list
Step 5: Go to STEP -3 upto n -1.
Step 6 : Read the searching element from the user
Step 7 : Assign to FALSE flag value
Step 8 : Search the element with using for loop until length of list
Step 9 : If value is found assign the flag value is true
Step10 : Then print the output of founded value an d position.
Step 11 : If value is not found then go to next step
Step 12 : Print the not found statement
PROGRAM :
a=[ ]
n=int(input("Enter number of
elements:")) for i in range(1,n+1):
b=int(input("Enter element:"))
[Link](b)
x = int(input("Enter number to search: "))
found = False
for i in range(len(a)):
if(a[i] = = x):
found = True
print("%d found at%dthposition"%(x,i))
break
if (found==False):
print("%d is not in list"%x)
20
OUTPUT 1:
OUTPUT 2:
Enter number of elements:5
Enter element:47
Enter element:99
Enter element:21
Enter element:35
Enter element:61
Enter number to search: 50
50 is not in list
RESULT:
Thus the program to perform linear Search is executed and the output is obtained.
21
[Link]. 3b. BINARY SEARCH
AIM:
PRELAB DISCUSSION:
The divide and conquer approach technique is followed by the recursive method. In this method, a
function is called itself again and again until it found an element in the list.
A set of statements is repeated multiple times to find an element's index position in the iterative method.
The while loop is used for accomplish this task.
Binary search is more effective than the linear search because we don't need to search each list index. The
list must be sorted to achieve the binary search algorithm.
ALGORITHM:
Then,
last index = mid-1
Go to Step:2
Else:
PROGRAM :
while(start_index<=last_index):
mid=int(start_index+last_index)/2)
if(element>arr[mid]):
22
start_index=mid+1
elif(element<arr[mid]):
last_index=mid-1
elif(element==arr[mid]):
return mid
else
return -1
arr=[]
n=input(“enter no of elements:”))
for i in range(1,n+1):
b=int(input(“enter element”))
[Link](b)
print(arr)
start_index=0
last_index=len(arr)-1
if (found = = -1):
print ("element not present in array")
else
print(“element is present at index”, found)
OUTPUT 1:
Enter number of elements:8
Enter element:11
Enter element:33
Enter element:44
Enter element:56
Enter element:63
Enter element:77
23
Enter element:88
Enter element:90
[11, 33, 44, 56, 63, 77, 88, 90]
Enter the element to be searched
63 element is present at index 4
OUTPUT 2:
Enter number of elements:7
Enter element:11
Enter element:15
Enter element:20
Enter element:25
Enter element:30
Enter element:40
Enter element:50
[11, 15, 20, 25, 30, 40, 50] Enter
the element to be searched 22
element not present in array
RESULT:
Thus the program to perform Binary Search is executed and the output is obtained.
24
[Link].4a SELECTION SORT
AIM:
To study and Implement Selection sort using python.
PRE LAB DISCUSSION
The provided Python code demonstrates the Selection Sort algorithm. Selection Sort has a time
complexity of O(n^2). In each iteration, the code finds the minimum element’s index in the
unsorted portion of the array and swaps it with the current index’s element. This gradually sorts
the array from left to right. The example initializes an array, applies the selectionSort function to
sort it, and then prints the sorted array in ascending order. The sorted array is obtained by
repeatedly finding the smallest element in the unsorted portion and placing it in its correct position,
resulting in an ordered array
ALGORITHM:
1. Start
2. Get the length of the array.
3. length = len(array) → 6
4. First, we set the first element as minimum element.
5. Now compare the minimum with the second element. If the second element is smaller than
the first, we assign it as a minimum.
6. After each iteration, minimum element is swapped in front of the unsorted array.
7. The second to third steps are repeated until we get the sorted array.
8. Stop
PROGRAM:
25
for j in range(ind + 1, size):
# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])
OUTPUT
RESULT:
Thus the python program is implemented by selection sort to sort the given array.
26
[Link].4b INSERTION SORT
AIM:
The insertion Sort function takes an array arr as input. It first calculates the length of the array (n).
If the length is 0 or 1, the function returns immediately as an array with 0 or 1 element is considered
already sorted.
For arrays with more than one element, the function proceeds to iterate over the array starting from
the second element. It takes the current element (referred to as the “key”) and compares it with the
elements in the sorted portion of the array that precede it. If the key is smaller than an element in
the sorted portion, the function shifts that element to the right, creating space for the key.
.
ALGORITHM:
1. Start
2. We start with second element of the array as first element in the array is assumed to be
sorted.
3. Compare second element with the first element and check if the second element is smaller
then swap them.
4. Move to the third element and compare it with the second element, then the first element
and swap as necessary to put it in the correct position among the first three elements.
5. Continue this process, comparing each element with the ones before it and swapping as
needed to place it in the correct position among the sorted elements.
6. Repeat until the entire array is sorted.
7. Stop
27
PROGRAM:
def insertionSort(arr):
n = len(arr) # Get the length of the array
if n <= 1:
return # If the array has 0 or 1 element, it is already sorted, so return
for i in range(1, n): # Iterate over the array starting from the second element
key = arr[i] # Store the current element as the key to be inserted in the right position
j = i-1
while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead
arr[j+1] = arr[j] # Shift elements to the right
j -= 1
arr[j+1] = key # Insert the key in the correct position
# Sorting the array [12, 11, 13, 5, 6] using insertionSort
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print('The array after sorting in Ascending Order by insertion sort is:')
print(arr)
OUTPUT
RESULT :
Thus the python program to perform sorting using insertion sort technique is executed
successfully.
28
EX. NO: 5a MERGE SORT
AIM
To perform sorting of the given data items using merge sort
ALGORITHM:
1. Start
3. Calculate the midpoint of the array if the low index is less than the high index.
4. Call the mergesort function on the left and right halves of the array.
6. Merge function creates two different arrays and copies the left and right halves into these arrays.
7. Iteration and comparison of both arrays are done.
9. Stop
29
PROGRAM:
# Python program for implementation of MergeSort
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i=0 # Initial index of first subarray
j=0 # Initial index of second subarray
k=l # Initial index of merged subarray
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
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
30
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr, l, r):
if l < r:
# Same as (l+r)//2, but avoids overflow for
# large l and h
m = l+(r-l)//2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")
31
OUTPUT:
Given array is 12 11 13 5 6 7
Sorted array is 5 6 7 11 12 13
RESULT
Thus the python program to perform sorting using merge sort technique is executed
successfully.
32
EX NO : 5b QUICK SORT
AIM:
To sort the given list of data items using quick sort techniques.
PRE LAB DISCUSSION
One of the most effective sorting algorithms is Quicksort, which is based on the divide-and-
conquer strategy. Quicksort makes some average memories complexity of O(n log n) and is
generally utilized practically speaking.
ALGORITHM:
Inputs:
A: an array of n elements
lo: the index of the first element of the sub-array to be sorted
hi: the index of the last element of the sub-array to be sorted
1. If lo is less than hi, then do the following:
o Call partition(A, lo, hi) and store the index of the pivot element in p.
o Recursively call quicksort(A, lo, p-1).
o Recursively call quicksort(A, p+1, hi).
Partition Algorithm:
1. Let pivot be the last element of the sub-array A[lo..hi].
2. Let i be the index of the first element of the sub-array.
3. For each j from lo to hi-1, do the following:
1. If A[j] <= pivot, then do the following:
1. Increment i.
2. Swap A[i] with A[j].
4. Swap A[i+1] with A[hi].
5. Return i+1.
PROGRAM:
# Python program for Quicksort
def quicksort(arr, lo, hi):
"""
Sorts the given array in ascending order using the Quicksort algorithm.
33
Parameters:
arr (list): The array to be sorted
lo (int): The index of the first element in the sub-array to be sorted
hi (int): The index of the last element in the sub-array to be sorted
"""
if lo < hi:
# Partition the array and get the index of the pivot element
p = partition(arr, lo, hi)
Parameters:
arr (list): The array to be partitioned
lo (int): The index of the first element in the sub-array to be partitioned
hi (int): The index of the last element in the sub-array to be partitioned
Returns:
int: The index of the pivot element after partitioning
"""
# Select the last element as the pivot
pivot = arr[hi]
i = lo - 1
OUTPUT
The given array before sorting is : [10, 7, 8, 9, 1, 5]
Sorted array by quick sort is: [1, 5, 7, 8, 9, 10]
RESULT :
Thus the python program for sorting the given data items using quick sort is executed
successfully.
35
EX NO: 6a IMPLEMENTING APPLICATIONS USING LISTS
Aim:
To write a python program to create, slice, change, delete and index elements using List.
PROGRAM:
print(“list is created in the name:list”)
list=[‘p’,’e’,’r’,’m’,’i’,’t’]
print(‘list created”,list)
print(“list indexing”,list[0])
print(“list slicing”,list[1:4])
list=[‘p’,’e’,’r’,’m’,’i’,’t’]
36
print("Given list",list)
list[0]=2
print("List Changing",list)
list[1:4]=[1,2,3]
print("List Changing",list)
list =
['p','e','r','m','i','t']
print("Given list",list)
list[0]=2
print("List Changing",list)
list[1:4]=[1,2,3]
print("List Changing",list)
list =
['p','e','r','m','i','t']
print("Given list",list)
[Link](['add','sub'])
print("List appending",list)
list = ['p','e','r','m','i','t' ]
print("Given list",list)
[Link]('p')
print("List Removing",list)
list = ['p','e','r','m','i','t']
print("Given list",list)
list[2:5] = []
print("List Delete",list)
37
OUTPUT :
List indexing p
List appending ['p', 'e', 'r', 'm', 'i', 't', ['add', 'sub']]
Given list[‘p’,’e’,’r’,’m’,’i’,’t’]
List Delete[‘p’,’e’,’t’]
RESULT:
Thus program to create, slice, change, delete and index elements using list is executed and the
output is obtained.
38
Ex. No: 6b IMPLEMENTING APPLICATIONS USING TUPLE
AIM:
To write a python program to create, slice, delete and index elements using Tuple.
PROGRAM1:
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
OUTPUT:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
PROGRAM3:
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
40
try:
print(tuple_)
except Exception as e:
print(e)
OUTPUT:
'tuple' object does not support item deletion
name 'tuple_' is not defined
PROGRAM4:
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
OUTPUT:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
RESULT:
Thus the program to illustrate the applications of tuple like create, slice, delete and index elements using
Tuple has been executed successfully.
41
Ex. No: 7 IMPLEMENTING APPLICATIONS USING SETS & DICTIONARIES
AIM:
To write a python program to check if a Given String Is Hetero gram or Not using sets. &
To write a python program to add items to the inventory, Update items to the inventory and to display items
using dictionaries
PRE LAB DISCUSSION:
A string is a heterogram if it has no alphabet that occurs more than once. For example, “NaukriLearning”
is not a heterogram. However, “blackhorse” is a heterogram. You can follow the below steps to check if a
given string is a heterogram or not.
Separate all the alphabets from other any other characters (using list comprehension)
Convert list of alphabets into set because set has unique elements (using set())
Using the ord() function which returns the ASCII value. If the ASCII value of the alphabet is greater than
or equal to that of ‘a’ and less than or equal to ‘z’ then add it to the list ‘alphabets’
PATHFINDER, DUMBWAITER, and BLACKHORSE are example of Heterogram
1. Start
2. Initialize an empty inventory (dictionary).
3. Display Menu
1. Show the following options:
1. Display Inventory
2. Add/Update Item
3. Remove Item
4. Exit
4. Choice Input
42
5. Process Based on Choice
if len(set(list_of_alphabets))==len(list_of_alphabets):
43
print ("Yes, the string '", input, "'is heterogram")
else:
print ("No, the string'", input, "'is not heterogram")
check_heterogram(str1)
check_heterogram(str2)
OUTPUT:
inventory = {}
def display_inventory():
if inventory:
for item, quantity in [Link]():
print(f"{item}: {quantity}")
else:
print("Inventory is empty.")
def add_or_update_item():
item = input("Enter item name: ")
quantity = int(input(f"Enter quantity for {item}: "))
inventory[item] = [Link](item, 0) + quantity
print(f"{item} updated with {inventory[item]} in stock.")
def remove_item():
item = input("Enter item to remove: ")
if item in inventory:
del inventory[item]
print(f"{item} removed.")
else:
44
print(f"{item} not found.")
def main():
while True:
print("\n1. Display Inventory\n2. Add/Update Item\n3. Remove Item\n4. Exit")
choice = input("Choose an option: ")
if choice == "1":
display_inventory()
elif choice == "2":
add_or_update_item()
elif choice == "3":
remove_item()
elif choice == "4":
break
else:
print("Invalid choice.")
OUTPUT:
1. Display Inventory
2. Add/Update Item
3. Remove Item
4. Exit
Choose an option: 1
Inventory is empty.
1. Display Inventory
2. Add/Update Item
3. Remove Item
4. Exit
Choose an option: 1
Inventory is empty.
1. Display Inventory
2. Add/Update Item
3. Remove Item
45
4. Exit
Choose an option: 2
Enter item name: Smartphone
Enter quantity for Smartphone : 40
Smartphone updated with 40 in stock.
1. Display Inventory
2. Add/Update Item
3. Remove Item
4. Exit
Choose an option: 1
Smartphone : 40
RESULT:
Thus the program to illustrate the applications of set has been executed successfully & thus the program to
illustrate the applications of dictionaries has been executed successfully
46
Ex. No: 8 IMPLEMENTING PROGRAMS USING FUNCTIONS
AIM:
PROGRAM/SOURCE CODE:
OUTPUT:
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4): 1
Enter first number: 5
Enter second number: 6
5.0 + 6.0 = 11.0
Let's do next calculation? (yes/no): yes
Enter choice(1/2/3/4): 3
Enter first number: 7
Enter second number: 7
7.0 * 7.0 = 49.0
Let's do next calculation? (yes/no):
Enter choice(1/2/3/4): 4
Enter first number: 4
Enter second number: 4
4.0 / 4.0 = 1.0
RESULT:
Thus the program is executed for design the calculator to perform arithmetic operations using
functions and the output is obtained.
48
Ex. No: 9 IMPLEMENTING PROGRAMS USING STRINGS
AIM:
PRELAB DISCUSSION
1. Understanding the Problem
Given an input string, the goal is to:
Identify the vowels (a, e, i, o, u).
Identify the consonants (all alphabets that are not vowels).
Count and display the number of vowels and consonants in the string.
String Manipulation
Strings in Python are sequences of characters.
They are immutable, but you can process them character by character.
Character Checking
Use the in keyword to check if a character belongs to a group (e.g., vowels).
Use the .isalpha() method to ensure the character is a letter.
Iteration
Iterate over each character in the string using a for loop.
Case-Insensitive Comparison
Convert the string to lowercase using .lower() to ensure consistency.
ALGORITHM:
Step 1: Initialize Counters:
Start with two counters, v_count and c_count, both set to zero. These will keep track of the
number of vowels and consonants.
Step 2: Define Vowels:
Create a string of all vowels (both uppercase and lowercase) for easy checking. For example,
vowels = "aeiouAEIOU".
Step 3: Iterate Through Each Character:
Loop through each character in the input string.
Step 4: Check if Character is Alphabetic:
For each character, first check if it’s a letter using isalpha() to ignore spaces, punctuation, and
other non-alphabetic characters.
Step 5: Determine if Vowel or Consonant:
If the character is a letter, check if it’s in the vowels string:
o If it is, increment the v_count.
o If it is not, it’s a consonant, so increment the c_count.
Step 6: Return or Print the Results:
Once the loop completes, print or return the values of v_count and c_count.
49
PROGRAM/SOURCE CODE:
def count_vowels_consonants(text):
vowels = "aeiouAEIOU"
v_count = 0
c_count = 0
for char in text:
if [Link](): # Check if the character is a letter
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
# Example usage
user_input = input("Enter a sentence: ")
vowels, consonants = count_vowels_consonants(user_input)
print(f"Vowels: {vowels}, Consonants: {consonants}")
OUTPUT:
RESULT:
Thus the program is executed for implement program using Strings to count Vowels and Consonants.
50
Ex. No: 10 IMPLEMENTING PROGRAMS USING WRITTEN MODULES AND
PYTHON STANDARD LIBRARIES (PANDAS,NUMPY, MATPLOTLIB,
SCIPY)
AIM:
To Implement python programusing written modules and Python Standard Libraries (pandas,numpy,
Matplotlib, scipy)
ALGORITHM
Step 1: Define the Modules:
Create separate modules for loading data, processing data, visualizing data, and performing
statistical analysis.
Step 2: Module 1: Data Loading (data_loader.py):
Define a function to load data from a CSV file using pandas.
If the file is not found, print an error message.
Step 3: Module 2: Data Processing (data_processor.py):
Define functions to:
o Calculate average scores for each subject using numpy.
o Retrieve scores for a specific student.
Step 4: Module 3: Data Visualization (data_visualizer.py):
Define a function to plot a bar chart of the average scores by subject using matplotlib.
Step 5: Module 4: Statistical Analysis (data_analyzer.py):
Define a function to perform a statistical t-test between scores of two subjects using scipy.
The function should return the t-statistic and p-value.
Step 6: Main Program (main_program.py):
Import the modules created in Steps 2–5.
Load the data using the data_loader module.
If data loading is successful:
o Calculate and print the average scores.
o Visualize the average scores by calling the plot_averages function from
data_visualizer.
o Retrieve and print scores for a specific student.
o Perform a t-test between scores of two subjects and print the results.
student_scores.csv
Name,Math,Science,English
Alice,88,92,85
Bob,76,85,80
Charlie,90,78,88
51
Daisy,65,70,60
Evan,95,89,94
import pandas as pd
def load_data(file_path):
"""Load data from a CSV file into a pandas DataFrame."""
try:
data = pd.read_csv(file_path)
return data
except FileNotFoundError:
print("File not found.")
return None
import numpy as np
def calculate_averages(data):
"""Calculate average scores for each subject."""
averages = {
"Math": [Link](data['Math']),
"Science": [Link](data['Science']),
"English": [Link](data['English'])
}
return averages
def plot_averages(averages):
"""Plot a bar chart of average scores."""
52
subjects = list([Link]())
scores = list([Link]())
# Load data
data = data_loader.load_data('student_scores.csv')
if data is not None:
# Calculate averages
averages = data_processor.calculate_averages(data)
print("Average Scores:", averages)
# Plot averages
data_visualizer.plot_averages(averages)
53
print("There is a statistically significant difference between Math and Science scores.")
else:
print("No statistically significant difference between Math and Science scores.")
OUTPUT
RESULT
Thus the python program is implemented and executed using all the written modules and Python
Standard Libraries (pandas,numpy, Matplotlib, scipy)
54
Ex. No: 11 IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
FILE HANDLING
AIM:
ALGORITHM
56
PROGRAM
import os
from datetime import datetime
def write_log(message):
"""Append a log entry with a timestamp to the log file."""
with open(LOG_FILE, "a") as log_file:
timestamp = [Link]().strftime("%Y-%m-%d %H:%M:%S")
log_file.write(f"{timestamp} - {message}\n")
print("Log written successfully.")
def read_logs():
"""Read and print all log entries from the log file."""
if [Link](LOG_FILE):
with open(LOG_FILE, "r") as log_file:
logs = log_file.readlines()
for log in logs:
print([Link]())
else:
print("Log file does not exist.")
57
print("No logs found within the specified date range.")
OUTPUT
Total Logs: 0
No logs found within the specified date range.
RESULT:
Thus python program to Implement time/technical applications using file handling is executed
successfully.
58
Ex. No: 12 IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
EXCEPTION HANDLING
AIM:
To write a python program to implement time/technical applications using exception handling
ALGORITHM
Specify the file paths for the input and output files.
o Handle ValueError:
59
If the conversion fails (e.g., non-integer data), print an error
message indicating invalid data and return None.
o If successful, perform calculations (e.g., squaring the integer).
o Append the result to the processed data list.
Return the processed data if all lines are processed successfully.
Call the read function to load data from the input file.
If None is returned, stop further processing and exit the program.
Call the process function to process the data.
If None is returned, stop further processing and exit the program.
Call the write function to save the processed data to the output file.
Display a final message indicating the end of the program.
Use a general Exception block to catch any unforeseen errors, display an error
message, and safely exit the program.
PROGRAM:
from datetime import datetime
def read_file(file_path):
"""Read lines from a file and return them as a
list.""" try:
with open(file_path, "r")
as file: data =
[Link]()
print("File read
successfully.") return data
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
60
except IOError:
print("Error: Issue with reading the file.")
return None
def process_data(data):
"""Convert each line to an integer and calculate the square."""
processed_data = []
try:
for line in data:
number = int([Link]()) # Attempt to convert to integer
squared = number ** 2 # Calculate square
processed_data.append(f"{number} squared is {squared}")
print("Data processed successfully.")
return processed_data
except ValueError as e:
print(f"Error: Invalid data. Cannot convert to integer. {e}")
return None
def main():
# Step 1: Read data from the input file
data = read_file(INPUT_FILE)
if data is None:
print("Terminating program due to read error.")
return
RESULT:
Thus a python program to implement time/technical applications using file handling is executed
successfully.
62
Ex. No: 13 CREATING AND INSTANTIATING CLASSES
AIM:
To write a python program for employee payroll processing using class and objects.
PRE LAB DISCUSSION:
Write a Python class Employee with attributes like emp_id, emp_name, emp_salary, and emp_department and
methods like calculate_emp_salary, emp_assign_department, and print_employee_details.
Use 'calculate_emp_salary' method takes two arguments: salary and hours_worked, which is the
number of hours worked by the employee. If the number of hours worked is more than 50, the
method computes overtime and adds it to the salary. Overtime is calculated as following formula:
overtime = hours_worked – 50
Overtime amount = (overtime * (salary / 50))
ALGORITHM:
Step1:Create a class employee
Step6:End
63
PROGRAM/SOURCE CODE :
class Employee:
[Link] = name
[Link] = emp_id
[Link] = salary
[Link] = department
overtime = 0
overtime = hours_worked - 50
[Link] = emp_department
def print_employee_details(self):
print(" ")
64
print("Original Employee Details:")
employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()
employee1.assign_department("OPERATIONS")
employee4.assign_department("SALES")
employee2.calculate_salary(45000, 52)
employee4.calculate_salary(45000, 60)
employee1.print_employee_details()
employee2.print_employee_details()
employee3.print_employee_details()
employee4.print_employee_details()
OUTPUT:
Name: ADAMS
ID: E7876
Salary: 50000
Department: ACCOUNTING
Name: JONES
ID: E7499
Salary: 45000
Department: RESEARCH
65
Name: MARTIN
ID: E7900
Salary: 50000
Department: SALES
Name: SMITH
ID: E7698
Salary: 55000
Department: OPERATIONS
Name: ADAMS
ID: E7876
Salary: 50000
Department: OPERATIONS
Name: JONES
ID: E7499
Salary: 46800.0
Department: RESEARCH
Name: MARTIN
ID: E7900
Salary: 50000
66
Department: SALES
Name:
SMIT
H ID:
E7698
Salary:
66000.0
Departme
nt:
SALES
RESULT:
Thus the Program was executed to create employee payroll processing using
classes and objects and the output is obtained
67
Ex. No: 14 DATA VISUALIZATION TECHNIQUES
AIM: To study and implement python program to implement various Data Visualizations using
python Libraries
1. Matplotlib
Matplotlib is a data visualization library and 2-D plotting library of Python It was initially released
in 2003 and it is the most popular and widely-used plotting library in the Python community. It comes
with an interactive environment across multiple platforms. Matplotlib can be used in Python scripts, the
Python and IPython shells, the Jupyter Notebook, web application servers, etc. It can be used to embed
plots into applications using various GUI toolkits like Tkinter, GTK+, wxPython, Qt, etc. So you can use
Matplotlib to create plots, bar charts, pie charts, histograms, scatterplots, error charts, power spectra,
stemplots, and whatever other visualization charts you want! The Pyplot module also provides a
MATLAB-like interface that is just as versatile and useful as MATLAB while being free and open
source.
import [Link] as plt
# Sample data
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]
# Create a line plot
[Link](x, y, label="y = x^2", color="b", marker="o")
# Add labels and title
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot: y = x^2")
[Link]()
# Display the plot
[Link]()
68
Example 2:
import [Link] as plt
# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 33]
# Create a bar chart
[Link](categories, values, color='red')
# Add labels and title
[Link]("Categories")
[Link]("Values")
[Link]("Bar Chart Example")
# Display the plot
[Link]()
69
2. Plotly
Plotly is a free open-source graphing library that can be used to form data visualizations. Plotly
([Link]) is built on top of the Plotly JavaScript library ([Link]) and can be used to create web-based
data visualizations that can be displayed in Jupyter notebooks or web applications using Dash or saved as
individual HTML files. Plotly provides more than 40 unique chart types like scatter plots, histograms, line
charts, bar charts, pie charts, error bars, box plots, multiple axes, sparklines, dendrograms, 3-D charts,
etc. Plotly also provides contour plots, which are not that common in other data visualization libraries. In
addition to all this, Plotly can be used offline with no internet connection.
Example 4
import [Link] as px
# Sample Data
df = [Link]()
# Create a scatter plot
fig = [Link](df, x='sepal_width', y='sepal_length', color='species',
title='Scatter Plot Example', labels={'sepal_width': 'Sepal Width', 'sepal_length': 'Sepal
Length'})
[Link]()
70
import plotly.graph_objects as go
# Data
labels = ['Category A', 'Category B', 'Category C', 'Category D']
values = [450, 300, 200, 50]
# Create a pie chart
fig = [Link]([Link](labels=labels, values=values, hole=0.4))
fig.update_layout(title='Pie Chart Example')
[Link]()
3. Seaborn
Seaborn is a Python data visualization library that is based on Matplotlib and closely integrated
with the NumPy and pandas data structures. Seaborn has various dataset-oriented plotting functions
that operate on data frames and arrays that have whole datasets within them. Then it internally performs
the necessary statistical aggregation and mapping functions to create informative plots that the user
71
desires. It is a high-level interface for creating beautiful and informative statistical graphics that are
integral to exploring and understanding data. The Seaborn data graphics can include bar charts, pie charts,
histograms, scatterplots, error charts, etc. Seaborn also has various tools for choosing colour palettes that
can reveal patterns in the data.
72
# Use keyword arguments for index, columns, and values
pivot = [Link](index='month', columns='year', values='passengers')
# Create a heatmap
[Link](data=pivot, cmap='coolwarm', annot=True, fmt='d')
[Link]('Seaborn Heatmap Example')
[Link]()
output
4. Squarify
# Data
sizes = [50, 25, 15, 10]
labels = ['Group A', 'Group B', 'Group C', 'Group D']
73
[Link]('off')
[Link]('Tree Map Example')
[Link]()
Result:
Thus the study and implementation of python program to display data visualizations using
python libraries.
74
VIVA QUESTIONS
1. Basics of Python
3. Control Flow
11. What is the difference between if, elif, and else in Python?
12. How does a while loop differ from a for loop in Python?
13. What is the purpose of the break and continue statements?
14. How can you iterate over a range of numbers in Python?
15. Explain list comprehensions with an example.
16. What are functions, and why are they used in Python?
17. How do you define and call a function in Python?
18. What are default arguments and keyword arguments in Python functions?
19. How do you import a module in Python? Give an example.
20. What is the difference between import and from ... import?
5. File Handling
7. Exception Handling
8. Python Collections
36. What is the difference between a list, tuple, set, and dictionary in Python?
37. How can you access elements in a tuple?
38. What is the significance of the keys() and values() methods in dictionaries?
39. How do you remove duplicate elements from a list in Python?
40. How is slicing implemented in Python lists?
9. Advanced Topics
46. What are some commonly used Python libraries for data analysis?
47. Explain the difference between NumPy and Pandas.
48. How is Django different from Flask?
49. What is the purpose of Matplotlib in Python?
50. How can you install third-party libraries in Python?
76