0% found this document useful (0 votes)
5 views11 pages

BCA4thSemPythonLabManualPartB

This document is a Python lab manual for BCA IV semester students, covering various topics such as regular expressions, lists, dictionaries, SQLite database operations, GUI creation with Tkinter, exception handling, and data visualization using Matplotlib. It includes code examples for each topic, demonstrating practical applications and operations. Additionally, it introduces NumPy and pandas for array and DataFrame manipulations.

Uploaded by

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

BCA4thSemPythonLabManualPartB

This document is a Python lab manual for BCA IV semester students, covering various topics such as regular expressions, lists, dictionaries, SQLite database operations, GUI creation with Tkinter, exception handling, and data visualization using Matplotlib. It includes code examples for each topic, demonstrating practical applications and operations. Additionally, it introduces NumPy and pandas for array and DataFrame manipulations.

Uploaded by

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

BCA IV SEM NEP Python: Lab Manual Part-B

#B1. Demonstrate usage of basic regular expression

import re

source="apple, banana, cherry,apple, cherry"

print("String source:")
print(source,"\n")

pattern="cherry"

# Example 1: Matching a pattern in a string


match=re.search(pattern,source)
if match:
print(f"Pattern found: \"{pattern}\" exists")

# Example 2: Searching for multiple occurrences of a pattern


findall=re.findall(pattern,source)
print(f"Occurrences of \"{pattern}\" : {findall}")

# Example 3: Replacing a pattern in a string


repStr="Mango"
newstr=re.sub(pattern,repStr,source)
print(f"Replaced string \"{pattern}\" by \"{repStr}\": {newstr}")

Page 1 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

#B2. Demonstrate use of advanced regular expression for data validation

import re

#verify email
'''email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

email=input("Enter email id to verify pattern : ")

if re.match(email_pattern, email):
print("Valid email id")
else:
print("Invalid email id")'''

# Verify password
password_pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{8,}$'

password=input("Enter password to verify the pattern : ")

if re.match(password_pattern, password):
print("Valid password id")
else:
print("Invalid password id")

Page 2 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

#B3. Demonstrare use of list

# Create an empty list


fruits = []
# Add fruits to the list
fruits.append("apple")
fruits.append("banana")
fruits.append("orange")

# Display the list


print("Fruits:", fruits)

# Accessing elements in the list


print("First fruit:", fruits[0])
print("Second fruit:", fruits[1])

# slicing
print(fruit[0:2])

# Modifying an element in the list


fruits[1] = "grape"
print("Modified fruits:", fruits)

# Removing an element from the list


removed_fruit = fruits.pop(2)
print("Removed fruit:", removed_fruit)
print("Updated fruits:", fruits)

# Checking if an element is in the list


if "apple" in fruits:
print("Apple is in the list.")
else:
print("Apple is not in the list.")

# Getting the length of the list


num_fruits = len(fruits)
print("Number of fruits:", num_fruits)

# Iterating over the list


print("All fruits:")
for fruit in fruits:
print(fruit)

# Sorting the list


fruits.sort()
print("Sorted fruits:", fruits)

Page 3 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

#B4. Demonstration of dictionary

# Creating an empty dictionary


person = {}

# Adding entries to the dictionary


person["name"] = "John Doe"
person["age"] = 25
person["city"] = "New York"

# Displaying the dictionary


print("Person Dictionary:", person)

# Retrieving values from the dictionary


print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])

# Updating values in the dictionary


person["age"] = 26
person["city"] = "Los Angeles"

# Displaying the updated dictionary


print("Updated Person Dictionary:", person)

# Deleting entries from the dictionary


del person["age"]
print("Person Dictionary (after deleting 'age'):", person)

# Checking if a key exists in the dictionary


if "name" in person:
print("'name' exists in the dictionary")

#traversing
for key,value in person.items():
print(key,value)

Page 4 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

#B5. Create sqlite database and perform operation on table

#B5. Create sqlite database and perform operation on table

import sqlite3

# Connect to the database (creates a new database if it doesn't exist)


conn = sqlite3.connect('example.db')

# Create a cursor object to execute SQL queries


cursor = conn.cursor()

# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
salary REAL
)
''')
def showRecords():
# Retrieve data from the table
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()

# Display the data


for row in rows:
print(row)
print()
# Insert data into the table
cursor.execute("INSERT INTO employees (name, age, salary) VALUES ('Alice', 30, 5000)")
cursor.execute("INSERT INTO employees (name, age, salary) VALUES (?, ?, ?)", ('Bob', 35, 6000))

# Commit the changes to the database


conn.commit()
showRecords()

# Update data in the table


cursor.execute("UPDATE employees SET salary = ? WHERE name = ?", (5500, 'Alice'))
conn.commit()
showRecords()

# Delete data from the table


cursor.execute("DELETE FROM employees WHERE name = ?", ('Bob',))
conn.commit()

Page 5 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

showRecords()

# Close the database connection


conn.close()

##B6. Create a GUI using Tkinter module

import tkinter as tk

# Create an instance of the Tk class


window = tk.Tk()

# Set the window title


window.title("My First GUI")

# Create a button widget


button = tk.Button(window, text="Click Me!")
lable=tk.Label(window)

# Define a function to handle button click event


def button_click():
lable.configure(text="Button event raised")

# Associate the button_click function with the button's click event


button.configure(command=button_click)

# Add the button to the window


button.pack()
lable.pack()

# Start the Tkinter event loop


window.mainloop()

Page 6 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

# B.7 Demonstrate exception in python

try:
#conde that may raise an exception
num1=int(input("Enter the first number : "))
num2=int(input("Enter the second number : "))

result=num1/ num2
print("Result: ", result)
print("Result" +result)

except ValueError:
print("Error: Invalid input. Please enter a valid number.")

except ZeroDivisionError:
print("Error: cannot divide by zero. ")

except Exception as e:
print("An erro occured: ", str(e))

finally:
print("Finally block : Error occures or not, i will be executed")

print("End of the program")

Page 7 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

#B8 . Draw line chart and bar chart using MatPlotLib

import matplotlib.pyplot as plt

while True:
print("1. Draw Line Chart")
print("2. Draw Bar Chart")
print("3. Exit")
choice=input("Enter the choice : ")

# Plot Line chart


if(choice=="1"):
x_values = [2018, 2019, 2020, 2021, 2022]
y_values = [160, 190, 100, 220, 220]

# Create line chart


plt.plot(x_values, y_values, marker='o', linestyle='--')

plt.xlabel('YEAR')
plt.ylabel('COUNT')
plt.title('SDC BCA STRENGTH')

plt.show()

#Plot Bar chart


elif(choice=="2"):
categories=["BCA", "BCOM", "BBA", "MCOM"]
values=[220,180,35,30]

# Create Bar chart


plt.bar(categories, values)

plt.title("SDC Courses and Head count")


plt.xlabel("Courses")
plt.ylabel("Head Count")

plt.show()

elif(choice=="3"):
print("Exiting......")
break

Page 8 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

else:
print("invalid choice")

#B9 . Draw Histogram and Pie chart using MatPlotLib

import matplotlib.pyplot as plt

while True:
print("1. Draw Histogram Chart")
print("2. Draw Pie Chart")
print("3. Exit")
choice=input("Enter the choice : ")

# Plot Histogram chart


if(choice=="1"):
# Example data
data = [1, 2, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 9, 10]

# Create the histogram


plt.hist(data, bins=10, edgecolor='black')

# Add labels and title


plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Example')

# Display the histogram


plt.show()

#Plot Pie chart


elif(choice=="2"):
# Example data
categories = ['BCA', 'BCOM', 'BBA', 'MCOM']
sizes = [45, 30, 15, 10] # These represent the proportions/percentages of each category

# Create the pie chart


plt.pie(sizes, labels=categories, autopct='%1.1f%%')

# Add a title
plt.title('XYZ College')

# Display the pie chart


plt.show()

Page 9 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

elif(choice=="3"):
print("Exiting......")
break

else:
print("invalid choice")

#B10. Create array using numpy and perform operation on array

# Step 1: Import NumPy


import numpy as np

# Step 2: Create an array


# Let's create a simple 1D array of integers from 1 to 5.
my_array = np.array([1, 2, 3, 4, 5])

# Step 3: Perform operations


# Let's demonstrate some basic operations on the array.

# Sum of all elements in the array


sum_of_elements = np.sum(my_array)
print("Sum of elements in the array:", sum_of_elements)

# Mean of all elements in the array


mean_of_elements = np.mean(my_array)
print("Mean of elements in the array:", mean_of_elements)

# Square of all elements in the array


squared_array = np.square(my_array)
print("Squared array:", squared_array)

# Element-wise addition of the array with itself


added_array = my_array + my_array
print("Added array:", added_array)

# Element-wise multiplication of the array with itself


multiplied_array = my_array * my_array
print("Multiplied array:", multiplied_array)

Page 10 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU
BCA IV SEM NEP Python: Lab Manual Part-B

# B11. Create DataFrame From Excel Sheet using pandas and perform operation on data Frames

# Step 1: Import pandas


import pandas as pd

# Step 2: Read data from Excel and create a DataFrame


df = pd.read_excel('data.xlsx')

# Display the DataFrame to see its content


print("Original DataFrame:")
print(df)

# Step 3: Perform operations on the DataFrame

# Calculate the mean age


mean_age = df['Age'].mean()
print("Mean age:", mean_age)

# Add a new column 'Age+10' with age incremented by 10 for each person
df['Age+10'] = df['Age'] + 10
print("DataFrame with new 'Age+10' column:")
print(df)

# Filter the rows where the salary is greater than 55000


high_salary_df = df[df['Salary'] > 55000]
print("DataFrame with high salary employees:")
print(high_salary_df)

##Note : openpy xl proble install following command


## pip install openpyxl

Page 11 of 11 Prepared by: Nagabhushan Hiremath


DEPT OF BCA, SDC, TUMKURU

You might also like