Yenepoya (Deemed to be University)
Recognized under Sec 3(A) of the UGC Act 1956 Re-
accredited by NAAC with ‘A+’ Grade
BCA-BSC 3RD SEM
LAB MANUAL
PYTHON PRORAMMING
____________________________________
📘 Part-A (25 Marks)
________________________________________
1. Write a user input program to check if a given number is a Prime Number or not.
2. Write a user input program to display the Fibonacci sequence up to n-th term.
3 a. Write a Python program to find the factorial of the given number.
b. Write a Python program to find the sum of n natural numbers.
4. Write a Python Program To find “Anagram” and “Palindrome”.
5. Write a Python program to add two matrices.
6. Write a User Input Program to Check if a giUse a Dictionary forAdding Items and Brands.
1.Add an item to the stationaries
2.Remove an item from stationaries
3.Display stationery
4.exit
7 a. Write a Python program to remove empty tuples from the list.
b. Write a Python program to find the largest and smallest element from the given list.
8. Write a Python program to merge two dictionaries.
9. Write a Python program to demonstrate Linear Search.
10. Write a Python program that opens a file and handles a FileNotFoundError exception if
the file does not exist.
________________________________________
📘 Part-B (25 Marks)
________________________________________
11. Write a python program to create a GUI application to implement road signs with the
appropriate foreground and background colours based on sign type stop, wait and Go
signals.
12. Write a Python program to create a GUI application using Tkinter that controls the text
font size in a label using a slider. Additionally, include a dropdown to change the font
colour and a button to randomly change the window's background colour.
13. Write a python script that performs the following operations on the SQLite database:
a. Creates a students table.
b. Inserts two records into the table.
c. Retrieves and displays the records.
d. Updates a student's grade.
e. Deletes a student record.
f. Closes the database connection.
14. Write a python program to create a database named “College.db” in sqlite. Create table
Teacher(t_id, t_name, salary, working_hours). Insert minimum 5 records to the teacher
table . Access Teacher table data and display data in descending order of salary. Display
name and working hours of teacher whose salary is highest.
15. Write a Python program to perform the following tasks related to employee data using
Pandas:
1. Create a DataFrame containing the following details of employees:
○ Name, Age, Salary , Department( IT, HR, Finance).
2. Save the DataFrame to a CSV file named employees.csv. 3. Read the DataFrame from
the employees.csv file.
4. Perform the following operations on the DataFrame:
○ Indexing: Select and display the Age column.
○ Selection: Select and display the Name and Department columns for all employees.
○ Filtering:
■ Display all employees who are older than 30.
■ Display all employees who work in the "IT"
department.
📘 Part-A (25 Marks)
1. Write a user input program to check if a given number is a Prime Number or not.
A number is said to be prime if it is only divisible by 1 and itself.
num = int(input("Enter a number: "))
if num == 1:
print("It is not prime")
elif num > 1:
for i in range(2, num):
if num % i == 0:
print(f"The number {num} is not a prime")
break
else:
print(f"The number {num} is a prime")
else:
print("Number should be greater than 1")
2. Write a user input program to display the Fibonacci sequence up to n-th term.
The Fibonacci sequence starts with 0 and 1. Each next term is the sum of the previous two.
num = int(input("Enter the Number of terms: "))
n1, n2 = 0, 1
if num <= 0:
print("Please enter a positive integer.")
elif num == 1:
print("Fibonacci Series:", n1)
else:
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
print(n3, end=" ")
n1, n2 = n2, n3
3a. Write a Python program to find the factorial of the given number.
Factorial of n is the product of all positive integers from 1 to n.
num = int(input("Enter the Number: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial is", fact)
3b. Write a Python program to find the sum of n natural numbers.
n = int(input("Enter a number: "))
sum1 = 0
while n > 0:
sum1 += n
n -= 1
print("The sum of first n natural numbers is", sum1)
4. Write a python Program To find “Anagram” and “Palindrome”
Anagram:
a word or phrase made by transposing the letters of another word or phrase
The word "secure" is an anagram of "rescue."
Palindrome:
a word, phrase, or sequence that reads the same backwards as forwards, e.g.
madam.
Code:
def anagram_check(s1, s2):
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
def palind_check(p1):
rev_p=p1[::-1]
if p1==rev_p:
print("It's a palindrome")
else:
print("It's not a palindrome")
# driver code
print("****Anagram****")
s1 =input("Enter string1 ")
s2 =input("Enter string2")
anagram_check(s1, s2)
print(" ")
#driver code- palindrome
print("****palindrome****")
p1=input("Enter string to check palindrome ")
palind_check(p1)
5 Write a Python program to add two matrices.
Matrix, a set of numbers arranged in rows and columns so as to form a
rectangular array
Code:
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
12
print(r)
6. Write a Menu Driven Program to add and Delete Stationary items. Use a Dictionary for
Adding Items and Brands.
a. Add an item to the stationaries
b. Remove an item from stationaries
c. Display stationery
d. exit
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Code:
dict={}
print("Choose the Option from the Menu")
print("--------------------------------------------")
print("1.Add an item to the stationaries ")
print("2.Remove an item from stationaries ")
print("3.Display stationery ")
print("4.exit")
#key - brand
#value - item
ch=int(input("Enter your Choice: "))
while(ch!=5):
if ch==1:
brand=input("Enter the brand [key] to be inserted : ")
item=input("Enter the item to be inserted : ")
dict[brand]=item
print("Added successfully" )
elif ch==2:
brand=input("Enter the brand [key] to be deleted: ")
if brand in dict.keys():
del dict[brand]
print(" Deleted successfully" )
elif brand not in dict.keys():
print("invalid key")
elif ch==3:
print(dict)
elif ch==4:
print( "Exiting!!!!!")
break
else:
5
print("Invalid choice....!! Choose option between 1 to 4")
ch=int(input("Enter your choice: "))
6. Output:
Choose the Option from the Menu
--------------------------------------------
1.Add an item to the stationaries
2.Remove an item from stationaries
3.Display stationery
4.exit
Enter your Choice: 1
Enter the brand [key] to be inserted : doms
Enter the item to be inserted : pen
Added successfully
Enter your choice: 1
Enter the brand [key] to be inserted : Apsara
Enter the item to be inserted : pencil
Added successfully
Enter your choice: 3
{'doms': 'pen', 'Apsara': 'pencil'}
Enter your choice: 2
Enter the brand [key] to be deleted: doms
Deleted successfully
Enter your choice: 3
{'Apsara': 'pencil'}
Enter your choice: 2
Enter the brand [key] to be deleted: doms
invalid key
Enter your choice: 4
Exiting!!!!!
7.A. Write a Python program to remove empty tuples from the list.
To remove empty tuples from the list.
Tuples- It is a collection of objects separated by commas. In some ways, a tuple is
similar to a Python list in terms of indexing, nested objects, and repetition but the main
difference between both is that the Python tuple is immutable(cannot change), unlike the
Python list which is mutable(can change)
Code
def Remove(tuples):
for i in tuples:
if(len(i) == 0):
tuples.remove(i)
return tuples
◦# Driver Code
◦tuples = [(), ('alex', '15', '8'), (), ('jhon', 'roy'),('tom', 'joy', '45'), ('',
''), ()] ◦print(Remove(tuples))
OUTPUT:
[('alex', '15', '8'), ('jhon', 'roy'), ('tom', 'joy', '45'), ('', '')]
7 b. Find the largest and smallest element from the given list
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :", max(lst),
"\nMinimum element in the list is :", min(lst))
OUTPUT
How many numbers: 4
Enter number 10
Enter number 45
Enter number 7
Enter number 58
Maximum element in the list is : 58 Minimum element in the list is : 7
8. Write a Python program to merge two dictionaries.
dict1 = {}
dict2 = {}
size1 = int(input("Enter the size of the first dictionary: "))
for i in range(size1):
key = input("Enter key: ")
value = input("Enter value: ")
dict1[key] = value
size2 = int(input("Enter the size of the second dictionary: "))
for i in range(size2):
key = input("Enter key: ")
value = input("Enter value: ")
dict2[key] = value
dict1.update(dict2)
print("Merged Dictionary:", dict1)
9. Write a Python program to demonstrate Linear Search.
def linear_search(list1, key):
for i in range(len(list1)):
if list1[i] == key:
return i
return -1
list1 = [1, 3, 5, 4, 7, 9]
key = int(input("Enter the element to search: "))
result = linear_search(list1, key)
if result == -1:
print("Element not found")
else:
print(f"Element found at index: {result}")
10. Write a Python program that opens a file and handles a FileNotFoundError
exception if the file does not exist.
def open_file(filename):
try:
file = open(filename, 'r')
contents = file.read()
print("File contents:")
print(contents)
file.close()
except FileNotFoundError:
print("Error: File not found.")
filename = input("Input a file name: ")
open_file(filename)
📙 Part-B (25 Marks)
11. Write a Python program to create a GUI application to implement road
signs with the appropriate foreground and background colours based on
sign type stop, wait and Go signals.
Code :
import tkinter as tk
class RoadSignApp:
def __init__(self, root):
self.root = root
self.root.title("Road Signs")
# Create buttons for each road sign type
self.create_buttons()
# Label to display the current sign
self.sign_label = tk.Label(self.root, text="", font=("Arial",
24)) self.sign_label.pack(pady=20)
def create_buttons(self):
# Stop Sign Button
stop_button = tk.Button(self.root, text="Stop",
command=self.show_stop_sign)
stop_button.pack(pady=10, padx=10)
# Wait Sign Button
wait_button = tk.Button(self.root, text="Wait",
command=self.show_wait_sign)
wait_button.pack(pady=10, padx=10)
# Go Sign Button
go_button = tk.Button(self.root, text="Go",
command=self.show_go_sign)
go_button.pack(pady=10, padx=10)
def show_stop_sign(self):
self.sign_label.config(text="STOP", fg="white", bg="red")
self.root.config(bg="red")
def show_wait_sign(self):
self.sign_label.config(text="WAIT", fg="black", bg="yellow")
self.root.config(bg="yellow")
17
def show_go_sign(self):
self.sign_label.config(text="GO", fg="white", bg="green")
self.root.config(bg="green")
if __name__ == "__main__":
root = tk.Tk()
app = RoadSignApp(root)
root.geometry("300x300")
root.mainloop()
OUTPUT
18
12. Write a Python program to create a GUI application using Tkinter that
controls the text font size in a label using a slider. Additionally, include a
dropdown to change the font colour and a button to randomly change the
window's background colour.
CODE:
import tkinter as tk
from tkinter import ttk
import random
class FontSizeApp:
def __init__(self, root):
self.root = root
self.root.title("Font Size Controller")
# Default settings
self.default_font_size = 16
self.default_font_color = "black"
self.default_bg_color = "white"
# Create a label to display the text
self.label = tk.Label(self.root, text="Welcome to Yenepoya",
font=("Arial", self.default_font_size),
fg=self.default_font_color) self.label.pack(pady=20)
# Create a slider to control font size
self.font_size_slider = tk.Scale(self.root, from_=10, to=100,
orient="horizontal", label="Font Size",
command=self.update_font_size)
self.font_size_slider.set(self.default_font_size)
self.font_size_slider.pack(pady=10)
# Dropdown to change text color
self.color_label = tk.Label(self.root, text="Choose Font Color:")
self.color_label.pack(pady=5)
self.color_var = tk.StringVar(value="black")
self.color_dropdown = ttk.Combobox(self.root,
textvariable=self.color_var, values=["black", "red", "blue", "green",
"purple"], state="readonly")
self.color_dropdown.pack(pady=5)
self.color_dropdown.bind("<<ComboboxSelected>>",
self.update_color)
# Button to change background color randomly
self.bg_button = tk.Button(self.root, text="Change Background Color",
command=self.change_bg_color)
19
self.bg_button.pack(pady=10)
def update_font_size(self, size):
# Update the font size of the label
self.label.config(font=("Arial", int(size)))
def update_color(self, event):
# Update the font color of the label
self.label.config(fg=self.color_var.get())
def change_bg_color(self):
# Change the background color to a random one
random_color = random.choice(["lightblue", "lightgreen",
"lightyellow", "lightpink", "lightgray"])
self.root.config(bg=random_color)
if __name__ == "__main__":
root = tk.Tk()
app = FontSizeApp(root)
root.geometry("400x300")
root.mainloop()
OUTPUT:
20
13. Write a python script that performs the following operations on the
SQLite database:
a. Creates a students table.
b. Inserts two records into the table.
c. Retrieves and displays the records.
d. Updates a student's grade.
e. Deletes a student record.
f. Closes the database connection.
CODE :
Python SQLite3 module is used to integrate the SQLite database with Python.It’s
used to execute SQL commands and queries, handle databases, and perform other
database management tasks.
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist) conn =
sqlite3.connect('students.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Create the 'students' table
cursor.execute('''CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY
KEY AUTOINCREMENT,
name TEXT NOT NULL,
grade TEXT NOT NULL
)''')
print("Table created successfully.")
# Insert two records into the 'students' table
cursor.execute("INSERT INTO students (name, grade) VALUES ('John Doe', 'A')")
cursor.execute("INSERT INTO students (name, grade) VALUES ('Jane Smith', 'B')")
conn.commit() # Commit the transaction
print("Records inserted successfully.")
# Retrieve and display the records
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nRecords in 'students' table:")
21
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Grade: {row[2]}")
# Update a student's grade
cursor.execute("UPDATE students SET grade = 'A+' WHERE
name = 'Jane Smith'")
conn.commit()
print("\nUpdated Jane Smith's grade to 'A+'.")
# Retrieve and display the updated records
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nRecords after updating grade:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Grade: {row[2]}")
# Delete a student record
cursor.execute("DELETE FROM students WHERE name = 'John
Doe'")
conn.commit()
print("\nDeleted John Doe's record.")
# Retrieve and display the records after deletion
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nRecords after deletion:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Grade: {row[2]}")
# Close the connection
conn.close()
print("\nDatabase connection closed.")
OUTPUT:
Table created successfully.
Records inserted successfully.
Records in 'students' table:
ID: 1, Name: John Doe, Grade: A
ID: 2, Name: Jane Smith, Grade: B
Updated Jane Smith's grade to 'A+'.
Records after updating grade:
ID: 1, Name: John Doe, Grade: A
ID: 2, Name: Jane Smith, Grade: A+
Deleted John Doe's record.
Records after deletion:
ID: 2, Name: Jane Smith, Grade: A+
Database connection closed.
23
14. Write a python program to create a database named “College.db” in sqlite.
Create table Teacher(t_id, t_name, salary, working_hours). Insert minimum
5 records to the teacher table . Access Teacher table data and display data in
descending order of salary. Display name and working hours of teacher
whose salary is highest.
#CODE
import sqlite3
# Step 1: Create a database named "College.db" and connect to it
connection = sqlite3.connect("College.db")
cursor = connection.cursor()
print("College Database Created Successfully")
# Step 2: Create table Teacher with specified columns
cursor.execute("""
CREATE TABLE IF NOT EXISTS Teacher (
t_id INTEGER PRIMARY KEY,
t_name TEXT NOT NULL,
salary REAL NOT NULL,
working_hours INTEGER NOT NULL
)
""")
print ("Table created ")
# Step 3: Insert minimum 5 records into the Teacher table
teachers = [
(1, "Alice", 50000, 8),
(2, "Bob", 45000, 7),
(3, "Charlie", 55000, 6),
(4, "Diana", 40000, 8),
(5, "Eve", 60000, 9)
]
cursor.executemany("""
INSERT OR IGNORE INTO Teacher (t_id, t_name, salary,
working_hours)
VALUES (?, ?, ?, ?)
""", teachers)
connection.commit()
print ("Data after Insertion")
cursor.execute("SELECT * FROM Teacher")
24
for row in cursor.fetchall():
print(row)
# Step 4: Access and display data in descending order of salary
print("Teacher Table Data in Descending Order of Salary:")
cursor.execute("SELECT * FROM Teacher ORDER BY salary
DESC") for row in cursor.fetchall():
print(row)
# Step 5: Display name and working hours of the teacher with the highest
salary
cursor.execute("""
SELECT t_name, working_hours
FROM Teacher
WHERE salary = (SELECT MAX(salary) FROM
Teacher) """)
highest_paid_teacher = cursor.fetchone()
print("\nTeacher with the Highest Salary:")
print(f"Name: {highest_paid_teacher[0]}, Working
Hours: {highest_paid_teacher[1]}")
# Close the connection
connection.close()
OUTPUT
College Database Created Successfully
Table created
Data after Insertion
(1, 'Alice', 50000.0, 8)
(2, 'Bob', 45000.0, 7)
(3, 'Charlie', 55000.0, 6)
(4, 'Diana', 40000.0, 8)
(5, 'Eve', 60000.0, 9)
Teacher Table Data in Descending Order of Salary:
(5, 'Eve', 60000.0, 9)
(3, 'Charlie', 55000.0, 6)
(1, 'Alice', 50000.0, 8)
(2, 'Bob', 45000.0, 7)
(4, 'Diana', 40000.0, 8)
Teacher with the Highest Salary:
Name: Eve, Working Hours: 9
25
15. Write a Python program to perform the following tasks related to
employee data using Pandas:
1. Create a DataFrame containing the following details of employees: ○
Name, Age, Salary , Department( IT, HR, Finance).
2. Save the DataFrame to a CSV file named employees.csv. 3.
Read the DataFrame from the employees.csv file.
4. Perform the following operations on the DataFrame:
○ Indexing: Select and display the Age column.
○ Selection: Select and display the Name and Department
columns for all employees.
○ Filtering:
■ Display all employees who are older than 30.
■ Display all employees who work in the "IT"
department.
CODE:
import pandas as pd
# Step 1: Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [23, 35, 45, 27, 32],
'Salary': [60000, 52000, 72000, 48000, 91000],
'Department': ['HR', 'IT', 'Finance', 'IT', 'HR']
}
df = pd.DataFrame(data)
# Step 2: Write the DataFrame to a CSV file
df.to_csv('employees.csv', index=False)
print("DataFrame saved to 'employees.csv'.")
# Step 3: Read the DataFrame from the CSV file
df_read = pd.read_csv('employees.csv')
print("\nDataFrame read from 'employees.csv':")
print(df_read)
# Step 4: Data Indexing, Selection, and Filtering
# Indexing: Select a specific column (Age)
print("\nIndexing: Select 'Age' column:")
print(df['Age'])
# Selection: Select multiple columns (Name and Department)
print("\nSelection: Select 'Name' and 'Department'
columns:") print(df[['Name', 'Department']])
26
# Row selection by index (select row at index 2)
print("\nSelect row at index 2:")
print(df.iloc[2])
# Filtering: Select rows where Age is greater than 30
print("\nFiltering: Rows where Age > 30:")
print(df[df['Age'] > 30])
# Filtering: Select rows where Department is 'IT'
print("\nFiltering: Rows where Department is 'IT':")
print(df[df['Department'] == 'IT'])