LAB RECORD
P23CAP12
PYTHON LABORATORY
MCA., Degree Practical Examination
Name ……………………………………………….
Branch ……………………………………………….
Semester ……………………………………………….
Reg .No. ……………………………………………….
Academic Year ……………………………………………….
Name ……………………………………………….
Reg. No. ……………………………………………….
Sem. /Branch ……………………………………………….
Sub.Code /Subject……………………………………………….
Certified that this is the Bonafide record of the Practical done for the above subject
inthe Laboratory during the period
……………………
Staff in Charge Head of the Department
Submitted for the University Practical Examination held at
DHANALAKSHMI SRINIVASAN ENGINEERING COLLEGE,
PERAMBALUR
on……………………
INTERNALEXAMINER EXTERNALEXAMINER
TABLEOF CONTENTS
PAGE STAFF
EXP.NO. NAMEOFTHE EXPERIMENT
NO. SIGN
PAGE STAFF
EXP.NO. NAMEOFTHE EXPERIMENT
NO. SIGN
1.Python programming using simple statements and
expressions(exchange the values of two variables, circulate the
values of n variables, distance between two points)
i) Exchange the values of two variables:
python
Copy code
# Initial values
a=5
b = 10
# Exchange values
a, b = b, a
print("After exchanging values:")
print("a =", a)
print("b =", b)
Output:
After exchanging values:
a = 10
b=5
ii) Circulate the values of n variables:
You can achieve this by shifting the values in a circular manner.#
Initialize variables
var1 = 1
var2 = 2
var3 = 3
# Store the initial values in a list
variables = [var1, var2, var3]
# Circulate values
temp =
variables[0]
for i in range(len(variables) - 1):
variables[i] = variables[i + 1]
variables[-1] = temp
# Print the circulated values
print("After circulating values:")
print("var1 =", variables[0])
print("var2 =", variables[1])
print("var3 =", variables[2])
Output:
After circulating values:
var1 = 2
var2 = 3
var3 = 1
iii).Calculate the distance between two points:
x1, y1 = 1, 2
x2, y2 = 4, 6
Formula:
(x1, y1) and p2 at (x2, y2), it is √((x1 - x2)² + (y1 - y2)²)
# Calculate the distance without using math
moduledistance = ((x2 - x1) * 2 + (y2 - y1) * 2)
** 0.5
print("Distance between the two points:", distance)
Output:
Distance between the two points: 3.7416573867739413
2. Scientific problems using Conditionals and Iterative loops.
num = 5
factorial = 1
if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("Factorial of 0 is 1.") else:
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
Output: 120
3.Linear search and Binary search
Linear search:
def LinearSearch(array, n, k):
for j in range(0, n):
if (array[j] == k):
return j
return -1
array = [1, 3, 5, 7, 9]
k=7
n = len(array)
result = LinearSearch(array, n, k)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)
Output:
Element found at index: 3
Binary search:
def binarySearch(arr, k, low, high):
while low <= high:
mid = low + (high - low)//2
if arr[mid] == k:
return mid
elif arr[mid] < k:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 3, 5, 7, 9]
k=5
result = binarySearch(arr, k, 0, len(arr)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
Output:
Element is present at index 2
4. Selection sort, Insertion sort
Selection sort:
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
If array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]
Insertion sort:
def insertionSort(arr):
n = len(arr) # Get the length of the array
if n <= 1:
return
for i in range(1,n):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Sorting the array [12, 11, 13, 5, 6] using insertionSort
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)
Output:
[5, 6, 11, 12, 13]
5. Merge Sort & Quick Sort
Merge Sort:
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# Into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i= j= k= 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
if name == '__main ':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is")
printList(arr)
mergeSort(arr)
print("\nSorted array is ")
printList(arr)
Output:
Quick Sort:
def quicksort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quicksort(left) + [pivot] + quicksort(right)
arr = [5, 1, 8, 3, 2]
print("original array:", arr)
sorted_arr = quicksort(arr)
print("Sorted array:", sorted_arr)
Output:
6. Implementing applications using Lists, Tuples
1. Lists
todo_list=[]
def add_task(task):
todo_list.append(task)
print(f'task "{task}." added.')
def view_tasks():
if todo_list:
print("\nto-do list")
for index, task in enumerate(todo_list,start=1):
print(f"{index}.{task}")
else:
print("your todo list is empty")
add_task("complted homework")
add_task("go to the gym")
add_task("buy groceries")
view_tasks()
Output:
2. Tuples
def add_contact(contacts, name, phone, email):
contact = (name, phone, email)
contacts.append(contact)
print(f'Contact "{name}" added.')
def display_contacts(contacts):
if contacts:
print("Contacts:")
for contact in contacts:
print(f"Name: {contact[0]}, Phone: {contact[1]}, Email: {contact[2]}")
else:
print("Your contacts list is empty.")
# Example Usage
contacts_list = []
add_contact(contacts_list, "John Doe", "555-1234", "
[email protected]")
add_contact(contacts_list, "Jane Smith", "555-5678", "
[email protected]")
display_contacts(contacts_list)
Output:
Name: John Doe, Phone: 555-1234, Email:
[email protected] Name: Jane Smith, Phone: 555-
5678, Email:
[email protected]7. Implementing applications using Sets, Dictionaries.
1. Sets:
def add_tags(article_tags, tags):
# Add tags to the set of article tags
article_tags.update(tags)
print(f'Tags {tags} added to the article.')
def display_tags(article_tags):
# Display the unique tags of the article
if article_tags:
print("Article Tags:")
for tag in article_tags:
print(tag)
else:
print("No tags for this article.")
# Example Usage
article_tags_set = set()
add_tags(article_tags_set, {"Python", "Programming", "Beginner"})
add_tags(article_tags_set, {"Python", "Data Science", "Intermediate"})
display_tags(article_tags_set)
Output:
Article Tags:
Programming, Beginner, Python, Intermediate, Data Science
ii) Dictionaries
contacts = {}
def add_contact():
name = input("Enter contact name: ")
number = input("Enter contact number: ")
contacts[name] = number
print(f"Contact {name} added successfully.")
def view_contacts():
print("Contacts:")
for name, number in contacts.items():
print(f"{name}: {number}")
def search_contact():
name = input("Enter contact name to search: ")
if name in contacts:
print(f"{name}: {contacts[name]}")
else:
print(f"Contact {name} not found.")
# Main loop
while True:
print("\nContact Book Menu:")
print("1. Add Contact")
print("2. View Contacts")
print("3. Search Contact")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
add_contact()
elif choice == "2":
view_contacts()
elif choice == "3":
search_contact()
elif choice == "4":
print("Exiting Contact Book. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Output :
8. Implementing programs using Functions.
def add(x, y):
return x +y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
if y != 0:
return x/y
else:
return "Error: Cannot divide by zero."
# Main function
def calculator():
while True:
print("\nCalculator Menu:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter your choice (1-5): "
if choice in {'1', '2', '3', '4'}:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"Result: {add(num1, num2)}")
elif choice == '2':
print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
elif choice == '5':
print("Exiting Calculator. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
# Run the calculator
calculator()
Output:
Calculator Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 1
Enter first number: 50
Enter second number: 60
Result: 110.0
Calculator Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 2
Enter first number: 1000
Enter second number: 5000
Result: -4000.0
Calculator Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 3
Enter first number: 50
Enter second number: 3
Result: 150.0
Calculator Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 4
Enter first number: 100
Enter second number: 0
Result: Error: Cannot divide by zero.
Calculator Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 5
9. Implementing programs using Strings
def count_words(sentence):
# Split the sentence into words
words = sentence.split()
# Count the number of
wordsnum_words =
len(words)
# Print the result
print(f"The number of words in the sentence is: {num_words}")
# Get user input
user_sentence = input("Enter a sentence: ")
# Call the function to count
words
count_words(user_sentence)
Output:
Enter a sentence: Good Morning
2
10. Implementing programs using written modules and Python
StandardLibraries (pandas, numpy, Matplotlib, scipy)
1. pandas
(i) Prepare the input data file (input_data.csv):
Name,Age
Alice,25
Bob,30
Charlie,35
David,22
Eve,28
ii) Create a Python script (main.py):
import pandas as pd
import my_data_processing_module as dp
import my_data_analysis_module as da
data = pd.read_csv('input_data.csv')
processed_data = dp.process_data(data)
analysis_result = da.analyze_data(processed_data)
analysis_result=pd.DataFrame(data)
analysis_result.to_csv('output_data.csv',index=False)
print("Data analysis completed and saved to 'output_data.csv'.")
iii) Create a custom module for data processing
(my_data_processing_module.py):
import pandas as pd
def process_data(data):
filtered_data = data[data['Age'] > 25]
print("Data where Value >25:")
print(filtered_data)
return filtered_data
Output
2. numpy
import numpy as np
def array_operations():
# Create NumPy arrays
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
# Perform array operations
sum_result = np.add(array1, array2)
product_result = np.multiply(array1, array2)
mean_result = np.mean(array1)
# Display the results
print("Array 1:", array1)
print("Array 2:", array2)
print("Sum of arrays:", sum_result)
print("Product of arrays:", product_result)
print("Mean of Array 1:", mean_result)
# Example usage
array_operations()
Output:
Array 1: [1 2 3 4 5]
Array 2: [ 6 7 8 9 10]
Sum of arrays: [ 7 9 11 13 15]
Product of arrays: [ 6 14 24 36 50]
Mean of Array 1: 3.0
3. Matplotlib
import matplotlib.pyplot as plt
import numpy as np
def plot_bar_chart_with_error_bars():
# Sample data
categories = ['Category A', 'Category B', 'Category C']
values = [5, 8, 6]
errors = [0.5, 1, 0.7]
# Plotting the bar chart with error bars
plt.bar(categories, values, yerr=errors, capsize=5, color='skyblue', label='Data')
# Adding labels and title plt.xlabel('Categories') plt.ylabel('Values')
plt.title('Bar Chart with Error Bars')
# Adding a legend
plt.legend()
# Display the graph
plt.show()
# Example usage
plot_bar_chart_with_error_bars()
Output
4. scipy
i) Create a Python script (main.py):
import my_scipy_module as sm # Custom module for numerical integration
# Step 2: Define the function to integrate
def func(x):
return x**2 # Example function to integrate: f(x) = x^2
# Step 3: Specify integration bounds
lower_bound = 0
upper_bound = 2
# Step 4: Use custom module to perform numerical integration
result = sm.perform_numerical_integration(func, lower_bound, upper_bound)
# Step 5: Display the integration result print("Result of numerical integration:",
result)
print("Numerical integration completed.")
ii) Create a custom module for scientific computations (my_scipy_module.py):
from scipy.integrate import quad
def perform_numerical_integration(func, lower_bound, upper_bound):
# Perform numerical integration using scipy's quad function
result, _ = quad(func, lower_bound, upper_bound)
return result
Output:
Result of numerical integration: 2.666666666666667
Numerical integration completed.
11. Implementing real–time/technical applications using File handling.
file_name = "inventory.txt"
def initialize_inventory():
try:
with open(file_name, "r") as file:
inventory = {}
for line in file:
item, quantity = line.strip().split(": ")
inventory[item] = int(quantity)
return inventory
except FileNotFoundError:
return {}
def save_inventory(inventory):
with open(file_name, "w") as file:
for item, quantity in inventory.items():
file.write(f"{item}: {quantity}\n")
def add_item(inventory, item, quantity):
if item in inventory:
inventory[item] += quantity
else:
inventory[item] = quantity
def remove_item(inventory, item, quantity):
if item in inventory:
if inventory[item] >= quantity:
inventory[item] -= quantity
else:
print(f"Not enough {item} in inventory.")
else:
print(f"{item} not found in inventory.")
try:
inventory = initialize_inventory()
while True:
print("\nMenu:")
print("1. Add Item")
print("2. Remove Item")
print("3. List Inventory")
print("4. Save and Quit")
choice = input("Enter your choice: ")
if choice == "1":
item = input("Enter item name: ")
quantity = int(input("Enter quantity to add: "))
add_item(inventory, item, quantity)
elif choice == "2":
item = input("Enter item name to remove: ")
quantity = int(input("Enter quantity to remove: "))
remove_item(inventory, item, quantity)
elif choice == "3":
print("\nInventory:")
for item, quantity in inventory.items():
print(f"{item}: {quantity}")
elif choice == "4":
save_inventory(inventory)
break
except KeyboardInterrupt:
print("\nOperation interrupted by the user.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Output:
Menu:
1. Add Item
2. Remove Item
3. List Inventory
4. Save and Quit
Enter your choice: 1
Enter item name: Abswana
Enter quantity to add: 10
Menu:
1. Add Item
2. Remove Item
3. List Inventory
4. Save and Quit
Enter your choice: 3
Inventory:
naveen: 1
Naveen : 2
Abswana: 10
Menu:
1. Add Item
2. Remove Item
3. List Inventory
4. Save and Quit
Enter your choice: 2
Enter item name to remove: naveen
Enter quantity to remove: 1
Menu:
1. Add Item
2. Remove Item
3. List Inventory
4. Save and Quit
Enter your choice: 4
12. Implementing real–time/technical applications using
Exceptionhandling.
import math
try:
# Prompt the user for input
user_input = float(input("Enter a number to calculate its square root: "))
# Check if the input is non-negative
if user_input < 0:
raise ValueError("Input must be a non-negative number.")
# Calculate the square
root result =
math.sqrt(user_input)
print(f"The square root of {user_input} is {result:.2f}")
except ValueError as ve:
print(f"ValueError: {str(ve)}")
except KeyboardInterrupt:
print("\nOperation interrupted by the user.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Output:
Enter a number to calculate its square
root: 25The square root of 25.0 is 5.0
13. Creating and Instantiating classes
class Person:
# Constructor method (_init_) to initialize class
attributesdef init (self, name, age):
self.name = name
self.age = age
# Method to display information about the person
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Instantiate objects of the
classperson1 = Person("Suriya", 30)
person2 = Person("Vijay", 25)
# Access object attributes and call
methodsperson1.display_info()
person2.display_info()
Output:
Name: Suriya, Age: 30
Name: Vijay, Age: 25
THANKING
YOU