[go: up one dir, main page]

0% found this document useful (0 votes)
3 views41 pages

Python Lab Manual

The document is a Python programming lab manual authored by Ajeetha Williams, detailing various programming exercises and examples. It includes tasks such as checking Fibonacci numbers, solving quadratic equations, implementing sorting algorithms, and working with data structures like stacks and databases. Additionally, it covers the use of regular expressions, GUI creation with Tkinter, and data manipulation with libraries like NumPy and Pandas.

Uploaded by

sg4450101
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)
3 views41 pages

Python Lab Manual

The document is a Python programming lab manual authored by Ajeetha Williams, detailing various programming exercises and examples. It includes tasks such as checking Fibonacci numbers, solving quadratic equations, implementing sorting algorithms, and working with data structures like stacks and databases. Additionally, it covers the use of regular expressions, GUI creation with Tkinter, and data manipulation with libraries like NumPy and Pandas.

Uploaded by

sg4450101
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/ 41

AJEETHA WILLIAMS, ASSISTANT PROFESSOR

DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

PYTHON PROGRAMS
Part-A
1. Check if a number belongs to the Fibonacci sequence
2. Solve Quadratic Equations
3. Find the sum of n natural numbers
4. Display Multiplication Tables
5. Check if a given number is a Prime Number or not
6. Implement a sequential search
7. Create a calculator program
8. Explore string functions
9. Implement Selection Sort
10. Implement Stack
11. Read and write into a file

Part-B
1. Demonstrate usage of basic regular expression
2. Demonstrate use of advanced regular expressions for data validation.
3. Demonstrate use of List
4. Demonstrate use of Dictionaries
5. Create SQLite Database and Perform Operations on Tables
6. Create a GUI using Tkinter module
7. Demonstrate Exceptions in Python
8. Drawing Line chart and Bar chart using Matplotlib
9. Drawing Histogram and Pie chart using Matplotlib
10. Create Array using NumPy and Perform Operations on Array
11. Create DataFrame from Excel sheet using Pandas and Perform Operations on
DataFrames

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 1


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

PART – A

1. Check if a number belongs to the Fibonacci sequence

n = int(input("Enter the number you want to check: "))


# variables for generating fibonacci sequence
f3 = 0
f1 = 1
f2 = 1
# 0 and 1 both are fibonacci numbers
if n == 0 or n == 1:
print("Given number is fibonacci number")
else:

# generating the Fibonacci numbers until the generated number is less than N
while f3 < n:
f3 = f1 + f2
f2 = f1
f1 = f3
if f3 == n:
print("Given number is Fibonacci number")
else:
print("No it’s not a Fibonacci number")

OUTPUT:

Enter the number you want to check: 3


Given number is Fibonacci number
Enter the number you want to check: 7
No it’s not a Fibonacci number

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 2


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

2. Solve Quadratic Equations

import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

OUTPUT:

Enter a: 2
Enter b: 3
Enter c: 4
The solution are (-0.75-1.1989578808281798j) and (-0.75+1.1989578808281798j)

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 3


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

3. Find the sum of n natural numbers

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


sum_of_numbers = 0
while num > 0:
sum_of_numbers += num
num -= 1
print("The sum is", sum_of_numbers)

OUTPUT:

Enter a natural number:5


The sum is 15

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 4


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

4. Display Multiplication Tables

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


# We are using "for loop" to iterate the multiplication 10 times
print("The Multiplication Table of: ", number)
for count in range(1, 11):
print(number, 'x', count, '=', number * count)

OUTPUT:

Enter a number: 5
The Multiplication Table of: 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 5


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

5. Check if a given number is a Prime Number or not

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


if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

OUTPUT:

Enter a number=3
3 is a prime number
Enter a number=6
6 is not a prime number

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 6


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

6. Implement a sequential search

print(end="Enter the Size: ")


arrSize = int(input())
print("Enter " + str(arrSize) + " Elements: ")
arr = []
for i in range(arrSize):
arr.append(input())
print("Enter an Element to Search: ")
elem = input()
chk = 0
for i in range(arrSize):
if elem == arr[i]:
index = i
chk = 1
break
if chk == 1:
print("\nElement Found at Index Number: " + str(index))
else:
print("\nElement doesn't found!")

OUTPUT:

Enter the Size: 3


Enter 3 Elements:
2
3
4
Enter an Element to Search:
1
Element doesn't found!

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 7


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

Enter the Size: 2


Enter 2 Elements:
1
2
Enter an Element to Search:
1
Element Found at Index Number: 0

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 8


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

7. Create a calculator program

def add(p, q):


return p + q

def subtract(p, q):


return p - q

def multiply(p, q):


# This function is used for multiplying two numbers
return p * q

def divide(p, q):


# This function is used for dividing two numbers
return p / q
while True:
print("Please select the operation.")
print("a. Add")
print("b. Subtract")
print("c. Multiply")
print("d. Divide")
print("e. Exit")
choice = input("Please enter choice (a/ b/ c/ d/e): ")
if choice == 'e':
print("Exit the program")
break
num_1 = int(input("Please enter the first number: "))
num_2 = int(input("Please enter the second number: "))

if choice == 'a':
print(num_1, " + ", num_2, " = ", add(num_1, num_2))

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 9


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

elif choice == 'b':


print(num_1, " - ", num_2, " = ", subtract(num_1, num_2))
elif choice == 'c':
print(num_1, " * ", num_2, " = ", multiply(num_1, num_2))
elif choice == 'd':
print(num_1, " / ", num_2, " = ", divide(num_1, num_2))

else:
print("This is an invalid input")

OUTPUT:

Please select the operation.


a. Add
b. Subtract
c. Multiply
d. Divide
e. Exit
Please enter choice (a/ b/ c/ d/e): a
Please enter the first number: 22
Please enter the second number: 11
22 + 11 = 33
Please select the operation.
a. Add
b. Subtract
c. Multiply
d. Divide
e. Exit
Please enter choice (a/ b/ c/ d/e): e
Exit the program

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 10


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

8. Explore string functions

str1 = "St. Vincent Pallotti college"


# length of a string
print("Length of the string", len(str1))
# uppercase conversion
print("upper case of the string", str1.upper())
# Lower conversion
print("Lower case of the string", str1.lower())
# Capitalize the first letter
print("Lower case of the string", str1.capitalize())
# Replace a substring
print("Replace substring 'St' with 'ST' : ", str1.replace("St","ST"))
# Given string is digit or not
print("Result= ", str1.isdigit())
# Given string is alpha numeric or not
print("Result is=", str1.isalnum())
# index of a string
print("Result is=", str1.index("college"))

OUTPUT:

Length of the string 28


upper case of the string ST. VINCENT PALLOTTI COLLEGE
Lower case of the string st. vincent pallotti college
Lower case of the string St. vincent pallotti college
Replace substring 'St' with 'ST' : ST. Vincent Pallotti college
Result= False
Result is= False
Result is= 21

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 11


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

9. Implement Selection Sort

def selection_sort(array):
for i in range(0, len(array) - 1):
smallest = i
for j in range(i + 1, len(array)):
if array[j] < array[smallest]:
smallest = j
array[i], array[smallest] = array[smallest], array[i]

array = input('Enter the list of numbers: ').split()


array = [int(x) for x in array]
selection_sort(array)
print('List after sorting is : ', end='')
print(array)

OUTPUT:

Enter the list of numbers: 12 34 11 45 23


List after sorting is : [11, 12, 23, 34, 45]

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 12


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

10. Implement Stack

list=[]
list.append(1) # append 1
print("push:", list)
list.append(2) # append 2
print("push:", list)
list.append(3) # append 3
print("push:", list)
list.pop() # pop 3
print("pop:", list)
print("peek:", list[-1]) # get top most element
list.pop() # pop 2
print("pop:", list)
print("peek:", list[-1]) # get top most element

OUTPUT:

push: [1]
push: [1, 2]
push: [1, 2, 3]
pop: [1, 2]
peek: 2
pop: [1]
peek: 1

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 13


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

11. Read and write into a file

with open("computer.txt", "w") as file:


file.write("Hello world!")
with open("computer.txt", "r")as file:
content = file.read()
print(content)

OUTPUT:

Hello world!

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 14


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

PART – B

1. Demonstrate usage of basic regular expression

import re
text = "Hello BCA Students! Welcome to 4th Sem"
#re.match() tries to match a pattern at the beginning of the string.//
match = re.match("Hello", text)
print("Match:", match.group() if match else None)
#re.search() searches the string for a match, and returns a match object if there is a
match.//
search = re.search("BCA", text)
print("Search:", search.group() if search else None)
#re.findall() returns a list containing all matches.//
findall = re.findall(r"[0-9]", text)
print("Findall:", findall)
#re.split() returns a list where the string has been split at each match.//
split = re.split(" ", text) # Splitting by space instead of "ls"
print("Split:", split)
#re.sub() replaces the matches with the text of choice.//
sub = re.sub("4th", "Fourth", text) # Replacing "4th" with "Fourth"
print("Sub:", sub)

OUTPUT:

Match: Hello
Search: BCA
Findall: ['4']
Split: ['Hello', 'BCA', 'Students!', 'Welcome', 'to', '4th', 'Sem']
Sub: Hello BCA Students! Welcome to Fourth Sem

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 15


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

2. Demonstrate use of advanced regular expressions for data validation.

import re
def validate_data():
email = input("Enter your email address: ")
phone = input("Enter your phone number: ")
url = input("Enter a URL: ")
password = input("Enter your password: ")
#Simple regular expressions for validation
email_regex = r'\S+@\S+\.\S+'
phone_regex = r'\d{10}'
url_regex = r'https?://(www\.)?\S+'
password_regex = r'.{8,}'#Any character, minimum length of 8
if not re.fullmatch(email_regex, email):
print("Invalid Email address")
if not re.fullmatch(phone_regex, phone):
print("Invalid Phone number")
if not re.fullmatch(url_regex, url):
print("Invalid URL")
if not re.fullmatch(password_regex, password):
print("Invalid password. It should be a minimum of 8 characters long.")
#Run the function
validate_data()

OUTPUT:

Enter your email address: abc.com


Enter your phone number: 5678901234
Enter a URL: www.google.com
Enter your password: secert
Invalid Email address

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 16


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

Invalid URL
Invalid password. It should be a minimum of 8 characters long.

Enter your email address: abc@gmail.com


Enter your phone number: 123456789
Enter a URL: http://www.google.com
Enter your password: Abcd@123
Invalid Phone number

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 17


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

3. Demonstrate use of List

#Define the list


my_list = [10, 20, 30, 3.142, 'Python', 'BCA']
print("Initial list:", my_list)
#Access list elements by index
print("Element at Index 0:", my_list[0])
print("Element at Index 2:", my_list[2])
#Change the value of a list item
my_list[4] = 'Java'
print("List after modifying an item:", my_list)
#Add an item to the end of the list and print
my_list.append('Skyward')
print("List after appending an item:", my_list)
#Remove an item from the list by value and print
my_list.remove('Java')
print("List after removing an item:", my_list)
#Remove an item from the list by index and print
del my_list[0]
print("List after deleting an item by index:", my_list)
#Pop an item and print
print("Popped item:", my_list.pop(1))
print("List after popping an item:", my_list)
#Print index of an item directly
print("Index of 'BCA':", my_list.index('BCA'))
#Print count of an item directly
print("Count of 3.142:", my_list.count(3.142))
#Print length of the list directly
print("Length of the list:", len(my_list))
#Reverse a list and print
my_list.reverse()

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 18


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

print("Reversed list:", my_list)


#Clear the list and print
my_list.clear()
print("List after clearing:", my_list)

OUTPUT:

Initial list: [10, 20, 30, 3.142, 'Python', 'BCA']


Element at Index 0: 10
Element at Index 2: 30
List after modifying an item: [10, 20, 30, 3.142, 'Java', 'BCA']
List after appending an item: [10, 20, 30, 3.142, 'Java', 'BCA', 'Skyward']
List after removing an item: [10, 20, 30, 3.142, 'BCA', 'Skyward']
List after deleting an item by index: [20, 30, 3.142, 'BCA', 'Skyward']
Popped item: 30
List after popping an item: [20, 3.142, 'BCA', 'Skyward']
Index of 'BCA': 2
Count of 3.142: 1
Length of the list: 4
Reversed list: ['Skyward', 'BCA', 3.142, 20]
List after clearing: []

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 19


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

4. Demonstrate use of Dictionaries

#Define a Dictionary
my_dict={'name':'Arun','age':40,'city':'Bangalore'}
print("Initial Dictionary:",my_dict)

# Access dictionary elements by key


print("Value for 'name':",my_dict['name'])
print("Value for 'age':",my_dict['age'])

#Get value with get method


print("Value for 'country':",my_dict.get('country'))

#Get Value with get mthod which provides a default value if the key is not in the
dictionary
print("Value for 'country' with default:",my_dict.get('country','India'))

#Change the value of a dictionary item


my_dict['age']=35
print("Dictionary after modifying an item:",my_dict)

#Add an item to the dictionary


my_dict['job']='Engineer'
print("Dictionary after adding an item:",my_dict)

# Remove an item from the dictionary by key


del my_dict['city']
print("Dictionary after deleting an item by key:",my_dict)

#Remove an iem using popmethod

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 20


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

print("Popped item:",my_dict.pop('job'))
print("Dictionary after popping an item:", my_dict)

#Get all keys, values and items


print("Keys:",list(my_dict.keys()))
print("Values:",list(my_dict.values()))
print("Items:",list(my_dict.items()))

#Get the number of items in the Dictionary


print("Number of items:",len(my_dict))

#Check if a key exists in the dictionary


print("'name' in dictionary:",'name' in my_dict)
print("'city' in dictionary:",'city' in my_dict)

#Merge two dictionaries


my_dict2={'country':'India','job':'Engineer'}
my_dict.update(my_dict2)
print("Dictionary after merging:",my_dict)

#Remove all items from the dictionary


my_dict.clear()
print("Dictionary after clearing:",my_dict)

OUTPUT:

Initial Dictionary: {'name': 'Arun', 'age': 40, 'city': 'Bangalore'}


Value for 'name': Arun
Value for 'age': 40
Value for 'country': None
Value for 'country' with default: India
Dictionary after modifying an item: {'name': 'Arun', 'age': 35, 'city': 'Bangalore'}

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 21


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

Dictionary after adding an item: {'name': 'Arun', 'age': 35, 'city': 'Bangalore', 'job':
'Engineer'}
Dictionary after deleting an item by key: {'name': 'Arun', 'age': 35, 'job': 'Engineer'}
Popped item: Engineer
Dictionary after popping an item: {'name': 'Arun', 'age': 35}
Keys: ['name', 'age']
Values: ['Arun', 35]
Items: [('name', 'Arun'), ('age', 35)]
Number of items: 2
'name' in dictionary: True
'city' in dictionary: False
Dictionary after merging: {'name': 'Arun', 'age': 35, 'country': 'India', 'job': 'Engineer'}
Dictionary after clearing: {}

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 22


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

5. Create SQLite Database and Perform Operations on Tables

import sqlite3
def display_rows(cursor):
rows=cursor.fetchall()
for row in rows:
print(row)

#Connect to the database or create it


conn=sqlite3.connect('employee.db')
cursor=conn.cursor()

#Create the 'emp' table


cursor.execute("""
CREATE TABLE emp(empno INTEGER PRIMARY KEY,
empname TEXT,
salary REAL,
department TEXT) """)
print("Table Created")

#Insert a record
cursor.execute("INSERT INTO emp VALUES(1,'Arun',50000,'IT')")
cursor.execute("INSERT INTO emp VALUES(2,'Asha',40000,'HR')")
cursor.execute("INSERT INTO emp VALUES(3,'Raj',55000,'Admin')")
conn.commit()
print("Records inserted")

#Select and Display records


cursor.execute("SELECT * FROM emp")
print("Records in the tables:")
display_rows(cursor)

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 23


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

#Update a record
cursor.execute("UPDATE emp SET salary=100000 WHERE empno=1")
conn.commit()
print("Record updated")

#Select and Display records after update


cursor.execute("SELECT * FROM emp")
print("Records in the table after update:")
display_rows(cursor)

#Delete a record
cursor.execute("DELETE FROM emp WHERE empno=1")
conn.commit()
print("Record deleted")

#Selct and display records after deletion


cursor.execute("SELECT* FROM emp")
print("Records in the table after deletion:")
display_rows(cursor)

#Drop the table


cursor.execute("DROP TABLE emp")
conn.commit()
print("Table dropped")

#CLOSE the Connection


conn.close()

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 24


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

OUTPUT:

Table Created
Records inserted
Records in the tables:
(1, 'Arun', 50000.0, 'IT')
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Record updated
Records in the table after update:
(1, 'Arun', 100000.0, 'IT')
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Record deleted
Records in the table after deletion:
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Table dropped

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 25


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

6. Create a GUI using Tkinter module

import tkinter as tk
from tkinter import messagebox,ttk
def submit():
messagebox.showinfo("Submitted","Form submitted successfully")

root=tk.Tk()
root.geometry("300x300")
root.title("Student Registration Form")
tk.Label(root,text="Student Name").grid(row=0)
tk.Label(root,text="Phone Number").grid(row=1)
tk.Label(root,text="Email Address").grid(row=2)
tk.Label(root,text="Residential Address").grid(row=3)
tk.Label(root,text="Gender").grid(row=4)
tk.Label(root,text="Course").grid(row=5)
tk.Label(root,text="Hobbies").grid(row=6)

name_entry=tk.Entry(root)
phone_entry=tk.Entry(root)
email_entry=tk.Entry(root)
address_text=tk.Text(root,width=20,height=5)

name_entry.grid(row=0,column=1)
phone_entry.grid(row=1,column=1)
email_entry.grid(row=2,column=1)
address_text.grid(row=3,column=1)

gender_var=tk.StringVar()
tk.Radiobutton(root,text="Male",variable=gender_var,value="Male").grid(row=4,colu
mn=1,sticky='w')

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 26


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

tk.Radiobutton(root,text="Female",variable=gender_var,value="Female").grid(row=4
,column=1,sticky='e')
course_var=tk.StringVar()
course_combobox=ttk.Combobox(root,textvariable=course_var)
course_combobox['values']=('BCA','BBA','BCOM')
course_combobox.grid(row=5,column=1)
hobbies={"Singing":tk.BooleanVar(),"Reading":tk.BooleanVar(),"Sports":tk.Boolean
Var()}
for idx,(hobby,var) in enumerate(hobbies.items()):

tk.Checkbutton(root,text=hobby,variable=var).grid(row=6+idx,column=1,sticky='w')

tk.Button(root,text="Submit",command=submit).grid(row=10,column=1)
root.mainloop()

OUTPUT:

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 27


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

7. Demonstrate Exceptions in Python

try:
num=int(input("Enter a number:"))
reciprocal=1/num
print("The Reciprocal of",num,"is",reciprocal)

except(ValueError,ZeroDivisionError):
print("Invalid input! Either it's not a number or the number is zero")

finally:
print("This statement is always executed")

OUTPUT:

Enter a number:2
The Reciprocal of 2 is 0.5
This statement is always executed

Enter a number:0
Invalid input! Either it's not a number or the number is zero
This statement is always executed

Enter a number:@@
Invalid input! Either it's not a number or the number is zero
This statement is always executed

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 28


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

8. Drawing Line chart and Bar chart using Matplotlib

Line Chart

import matplotlib.pyplot as plt


# Prepare the data
x=[1,2,3,4,5]
y=[1,4,9,16,25]

#plot the line graph


plt.plot(x,y)

#Add title and axis labels


plt.title("Simple Line Graph")
plt.xlabel("Number")
plt.ylabel("Square")

#Show the plot


plt.show()

#Save the plot


plt.savefig("Simple_line_graph.png")

Bar Chart

# Import matplotlib library


import matplotlib.pyplot as plt

#Given courses and count


courses=['BCA','BCM','BBA','BSC','BA']
count=[120,180,60,30,80]

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 29


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

# Create a barchart
plt.bar(courses,count,color='maroon',width=0.4)

#Title and labels


plt.xlabel("Courses")
plt.ylabel("Count")
plt.title("Count of Students in different courses")

#Display the bar chart


plt.show()

OUTPUT:

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 30


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 31


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

9. Drawing Histogram and Pie chart using Matplotlib

Histogram

# Import required libraries


import matplotlib.pyplot as plt

#This is our data


ages=[25,22,23,23,30,31,22,35,34,56,27,45,41,19,19,26,32,33,45,40]
# Create histogram
plt.hist(ages,bins=5,edgecolor='black')

#Add title and labels


plt.title('Ages of Customers')
plt.xlabel('Age')
plt.ylabel('Number of Customers')

#Show the plot


plt.show()

Piechart

import matplotlib.pyplot as plt

#Data
languages=['Python','Java','C++','Javascript','C#']
votes=[250,150,100,75,50]

#Create a pie chart


plt.figure(figsize=[5,5])
plt.pie(votes,labels=languages,autopct='%1.1f%%')

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 32


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

plt.title('Favorite Programming Languages')


plt.show()

OUTPUT:

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 33


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

10. Create Array using NumPy and Perform Operations on Array

#Import Numpy library


import numpy as np

#Create two arrays


a=np.array([1,2,3])
b=np.array([4,5,6])

#Perform arithmetic operations


print("Addition:",a+b)
print("Subtraction:",a-b)
print("Multiplication:",a*b)
print("Division:",a/b)

#Perform relational operations


print("a Greater than b:",a>b)
print("a Less than b:",a<b)
print("a Equal to b:",a==b)
print("a Not Equal to b:",a!=b)

#Perform logical operations


print("Logical OR:",np.logical_or(a,b))
print("Logical AND:",np.logical_and(a,b))
print("Logical NOT:",np.logical_not(a))

#Perform aggregation operations


print("Sum of a:",np.sum(a))
print("Max of b:",np.max(b))

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 34


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

print("Min of a:",np.min(a))
print("Average of b:",np.average(b))

# Perform matrix operations


print("Matrix Addition:\n",a+b)
print("Matrix Subtraction:\n",a-b)
print("Matrix Multiplication(element_wise:\n",a*b)
print("Matrix Multiplcation:\n",np.matmul(a,b))
print("Transpose of a:\n",np.transpose(a))

#Perform Statistical funtions


print("Standard Deviation:",np.std(a))
print("Variance:",np.var(a))
print("Median:",np.median(a))

#Reshape array
c=a.reshape((3,1))
print("Reshaped a:",c)

#Stack arrays
print("Horizontal stack:\n",np.hstack((a,b)))
print("Vertical stack:\n",np.vstack((a,b)))

#Split array
d=np.array([[1,2,3,4],[5,6,7,8]])
print("Horizontal Split:\n",np.hsplit(d,2))
print("Vertical Split:\n",np.vsplit(d,2))

#Broadcasting
print("Broadcasting addition:\n",a+5)

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 35


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

OUTPUT:

Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [ 4 10 18]
Division: [0.25 0.4 0.5 ]
a Greater than b: [False False False]
a Less than b: [ True True True]
a Equal to b: [False False False]
a Not Equal to b: [ True True True]
Logical OR: [ True True True]
Logical AND: [ True True True]
Logical NOT: [False False False]
Sum of a: 6
Max of b: 6
Min of a: 1
Average of b: 5.0
Matrix Addition:
[5 7 9]
Matrix Subtraction:
[-3 -3 -3]
Matrix Multiplication(element_wise:
[ 4 10 18]
Matrix Multiplcation:
32
Transpose of a:
[1 2 3]
Standard Deviation: 0.816496580927726
Variance: 0.6666666666666666
Median: 2.0
Reshaped a: [[1]
[2]

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 36


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

[3]]
Horizontal stack:
[1 2 3 4 5 6]
Vertical stack:
[[1 2 3]
[4 5 6]]
Horizontal Split:
[array([[1, 2],
[5, 6]]), array([[3, 4],
[7, 8]])]
Vertical Split:
[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
Broadcasting addition:
[6 7 8]

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 37


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

11. Create DataFrame from Excel sheet using Pandas and Perform Operations on
DataFrames

#Import pandas library


import pandas as pd

#Read DataFrame from excel file


df=pd.read_excel("emp.xlsx")

#Data selection of single column


print("\n Single Column: \n",df['Name'])

#Data selection of Double Columns


print("\n Double columns: \n",df[['Name','Gender']])

#Select first row by index label using .loc[]


print("\n First row using .loc[]: \n",df.loc[0])

#Select first row by position using .iloc[]


print("\n First row using .iloc[]: \n",df.iloc[0])

#Slice the first two rows and select 'Student Name' and 'Age' columns
print("The first two rows of Name and Age Columns:")
print(df[:2][['Name','Age']])

#Filtering based on age>30


print("\nFiltered DataFrame(Age>30): \n",df[df['Age']>30])

#Grouping based on Course and Age


grouped_df=df.groupby('Gender')['Age'].mean()
print("\nGrouped DataFrame (based on 'Gender' and 'Age'):\n",grouped_df)

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 38


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

#Sorting by index
df_by_index=df.sort_index(ascending =False)
print("\n DataFrame sorted by index: \n",df_by_index)

#Sorting by values
df_by_value=df.sort_values(by='Age')
print("\n DataFrame sorted by 'Age' column: \n",df_by_value)

OUTPUT:

Single Column:
0 Arun
1 Raj
2 Rani
3 Rita
4 Ashok
5 Sneha
Name: Name, dtype: object

Double columns:
Name Gender
0 Arun M
1 Raj M
2 Rani F
3 Rita F
4 Ashok M
5 Sneha F

First row using .loc[]:


Name Arun

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 39


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

Age 45
Gender M
Name: 0, dtype: object

First row using .iloc[]:


Name Arun
Age 45
Gender M
Name: 0, dtype: object
The first two rows of Name and Age Columns:
Name Age
0 Arun 45
1 Raj 43

Filtered DataFrame(Age>30):
Name Age Gender
0 Arun 45 M
1 Raj 43 M
5 Sneha 42 F

Grouped DataFrame (based on 'Gender' and 'Age'):


Gender
F 31.666667
M 38.333333
Name: Age, dtype: float64

DataFrame sorted by index:


Name Age Gender
5 Sneha 42 F
4 Ashok 27 M
3 Rita 29 F
2 Rani 24 F

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 40


AJEETHA WILLIAMS, ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE, ST. VINCENT PALLOTTI COLLEGE

1 Raj 43 M
0 Arun 45 M

DataFrame sorted by 'Age' column:


Name Age Gender
2 Rani 24 F
4 Ashok 27 M
3 Rita 29 F
5 Sneha 42 F
1 Raj 43 M
0 Arun 45 M

IV SEM BCA PYTHON PROGRAMMING LAB MANUAL 41

You might also like