0% found this document useful (0 votes)
7 views46 pages

Practical File

This document is a practical file for Computer Science submitted by Upraj S. Bedi from Delhi Public School, Dwarka for the session 2025-26. It includes a certificate of completion, acknowledgments, and a detailed table of contents outlining various programming tasks and exercises in Python and SQL. The document covers topics such as functions, data structures, file handling, and operator implementation, along with sample code and outputs for each task.

Uploaded by

uprajsingh1403
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)
7 views46 pages

Practical File

This document is a practical file for Computer Science submitted by Upraj S. Bedi from Delhi Public School, Dwarka for the session 2025-26. It includes a certificate of completion, acknowledgments, and a detailed table of contents outlining various programming tasks and exercises in Python and SQL. The document covers topics such as functions, data structures, file handling, and operator implementation, along with sample code and outputs for each task.

Uploaded by

uprajsingh1403
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

DELHI PUBLIC SCHOOL

DWARKA

COMPUTER SCIENCE
PRACTICAL FILE
SESSION:2025-26

SUBMITTED BY:

NAME: Upraj S. Bedi


CLASS:XII-C

ROLL_NO:42
CERTIFICATE

This is to verify that UPRAJ S. BEDI of class XII-C of Delhi Public


School , Dwarka has successfully , solely and sincerely completed the
practical file for the computer science under the direct supervision of
the undersigned as per the requirements from the board
examination.

Mr. Amit Dua


(Subject Teacher)
ACKNOWLEDGEMENT

I , Upraj S. Bedi , would like to express my gratitude towards our


Principal Ms. Priya Narayanan and Mr. Amit Dua for guiding me
through this practical and helping me gain knowledge on this subject.
I am extremely thankful to my parents who gave me motivation and
resources the complete this practical file
TABLE OF CONTENTS
[Link] Topic

Q1 Creating a Function to receive some values and returns the result

Q2 Creating a Function to explain the use of Global and Local variables in function

Q3 Creating a menu driven program to implement List

Q4 Creating a menu driven program to implement Tuple

Q5 Creating a menu driven program to implement Dictionary

Q6 Creating a python program to implement python Operators

Q7 Creating a python program to generate random numbers

Q8 Creating a python program to read a text file line by line

Q9 Creating a python program to read a text file word by word

Q10 Creating a python program to copy particular lines of a text file into another text file

Q11 Creating a python program to create and search records in binary file

Q12 Creating a python program to create and update/modify records in binary file

Q13 Creating a python program to create and search employee’s record in csv file

Q14 Creating a python program to implement stack operations (List)

Q15 Creating a python program to implement stack operations (Dictionary)

Q16 Implementing MySQL in Python

Q17 SQL COMMANDS EXERCISE – 1

Q18 SQL COMMANDS EXERCISE – 2

Q19 SQL COMMANDS EXERCISE – 3

Q20 SQL COMMANDS EXERCISE – 4

Q21 SQL COMMANDS EXERCISE – 5


Q1: Create a python function to receive some values and return the result:
CODE:
def add(a,b):
c=a+b
return c
def subtract(a,b):
c=a-b
return c
def div(a,b):
c=a/b
return c
def multiply(a,b):
c=a*b
while True:
print('\n\tMENU')
print('\n\[Link]')
print('\n\[Link]')
print('\n\[Link]')
d=int(input('enter number: '))
if d not in (1,2):
print('\n\t\t***END***')
break
if d==1:
a=float(input('enter first number'))
b=float(input('enter second number'))
print(add(a,b))
if d==2:
a=float(input('enter first number'))
b=float(input('enter second number'))
print(subtract(a,b))

OUTPUT:
MENU

[Link]

[Link]

[Link]
enter number: 1
enter first number110
enter second number25
135.0

MENU

[Link]

[Link]

[Link]
enter number: 2
enter first number 15
enter second number10
5.0
Q2: Create a python function to explain the use of global and local variables in function:

CODE:

x=10

def f():
y=5
global x
print('inside function')
print(f'global variable x:{x}')
print(f'global variable y:{y}')
x=x+15
f()
print(f'modified variable inside function x:{x}')

OUTPUT:

inside function:
global variable x:10
global variable y:5
modified variable inside function x:25

Q3: Create a menu driven program to implement a list:

CODE:

l=[]
def f1():
global l
try:
element=input('enter element to add in the list')
[Link](element)
print(f'element:{element} added in list')
except:
print('element not added!')
def f2():
global l
try:
element=input('enter element to remove')
while True:
[Link](element)
if element not in l:
break
print(f'all occurences of element:{element} is removed')
except:
print('element not removed!')
def f3():
global l
print(l)
def f4():
global l
try:
element=input('enter element u want to find')
if element in l:
print(f'{element} is present in list')
except:
print(f'{element} not in list!')
def f5():
global l
print(f'length of list is {len(l)}')

while True:
print('\n\tMENU')
print('\n\[Link]')
print('\n\[Link] an element to the list')
print('\n\[Link] an element to the list')
print('\n\[Link] the list')
print('\n\[Link] for an element in list')
print('\n\[Link] the length of the list')

a=int(input('enter num'))
if a not in (1,2,3,4,5):
print('\n\t***THE END***')
break
if a==1:
f1()
if a==2:
f2()
if a==3:
f3()
if a==4:
f4()
if a==5:
f5()
OUTPUT:

MENU

[Link]

[Link] an element to the list

[Link] an element to the list

[Link] the list

[Link] for an element in list

[Link] the length of the list

enter num1
enter element to add in the list hello
element: hello added in list

MENU

[Link]

[Link] an element to the list

[Link] an element to the list

[Link] the list

[Link] for an element in list

[Link] the length of the list


enter num3
[' hello']
Q4:Create a menu driven program to implement tuple:

CODE:
t = ()

def add_tuple():
global t
element = input("Enter element to add to the tuple: ")
t += (element,)
print(f"Element '{element}' added.")

def remove_tuple():
global t
element = input("Enter element to remove: ")
if element in t:
t = tuple(x for x in t if x != element)
print(f"All occurrences of '{element}' have been removed.")
else:
print(f"'{element}' not found in the tuple.")

def display_tuple():
print("Current tuple:", t)

def search_tuple():
element = input("Enter element to search for: ")
for i in range(len(t)):
if t[i] == element:
print(f"'{element}' found at index {i}")
return
print(f"'{element}' not found.")

def length_tuple():
print(f"Length of tuple is: {len(t)}")

while True:
print("\n========= MENU =========")
print("0. Exit")
print("1. Add an element")
print("2. Remove an element")
print("3. Display the tuple")
print("4. Search for an element")
print("5. Get tuple length")

try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == 0:
print("*** THE END ***")
break
elif choice == 1:
add_tuple()

elif choice == 2:
remove_tuple()

elif choice == 3:
display_tuple()

elif choice == 4:
search_tuple()

elif choice == 5:
length_tuple()

else:
print("Invalid choice. Try again.")

OUTPUT:

========= MENU =========


0. Exit
1. Add an element
2. Remove an element
3. Display the tuple
4. Search for an element
5. Get tuple length
Enter your choice: 1
Enter element to add to the tuple: 1
Element '1' added.

========= MENU =========


0. Exit
1. Add an element
2. Remove an element
3. Display the tuple
4. Search for an element
5. Get tuple length
Enter your choice: 3
Current tuple: ('1',)
Q5: Create a menu driven program to implement dictionary:

CODE:
d = {}

def add_key_value():
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value
print(f"'{key}': '{value}' added to dictionary.")

def remove_key():
key = input("Enter key to remove: ")
if key in d:
del d[key]
print(f"Key '{key}' removed.")
else:
print(f"Key '{key}' not found.")

def display_dictionary():
print("Current dictionary:")
for key, value in [Link]():
print(f"{key}: {value}")

def search_key():
key = input("Enter key to search: ")
if key in d:
print(f"Found '{key}' with value '{d[key]}'")
else:
print(f"Key '{key}' not found.")

def dictionary_size():
print(f"Dictionary has {len(d)} entries.")

while True:
print("\n========= MENU =========")
print("0. Exit")
print("1. Add a key-value pair")
print("2. Remove a key")
print("3. Display dictionary")
print("4. Search for a key")
print("5. Dictionary size")

try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Enter a valid number.")
continue
if choice == 0:
print("*** THE END ***")
break
elif choice == 1:
add_key_value()

elif choice == 2:
remove_key()

elif choice == 3:
display_dictionary()

elif choice == 4:
search_key()

elif choice == 5:
dictionary_size()

else:
print("Invalid choice.")

OUTPUT:

========= MENU =========


0. Exit
1. Add a key-value pair
2. Remove a key
3. Display dictionary
4. Search for a key
5. Dictionary size
Enter your choice: 1
Enter key: 2
Enter value: Tuesday
'2': 'Tuesday' added to dictionary.

========= MENU =========


0. Exit
1. Add a key-value pair
2. Remove a key
3. Display dictionary
4. Search for a key
5. Dictionary size
Enter your choice: 3
Current dictionary:
1: Monday
2: Tuesday
Q6: Create program to implement python operators:

CODE:
def arithmetic_operators(a, b):
print("\nArithmetic Operators:")
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b if b != 0 else 'undefined'}")
print(f"{a} % {b} = {a % b if b != 0 else 'undefined'}")
print(f"{a} ** {b} = {a ** b}")
print(f"{a} // {b} = {a // b if b != 0 else 'undefined'}")

def comparison_operators(a, b):


print("\nComparison Operators:")
print(f"{a} == {b} -> {a == b}")
print(f"{a} != {b} -> {a != b}")
print(f"{a} > {b} -> {a > b}")
print(f"{a} < {b} -> {a < b}")
print(f"{a} >= {b} -> {a >= b}")
print(f"{a} <= {b} -> {a <= b}")

def logical_operators(a, b):


print("\nLogical Operators:")
print(f"{a} > 0 and {b} > 0 -> {a > 0 and b > 0}")
print(f"{a} > 0 or {b} > 0 -> {a > 0 or b > 0}")
print(f"not ({a} > 0) -> {not (a > 0)}")

def assignment_operators():
print("\nAssignment Operators:")
x = 5
print(f"x = {x}")
x += 3; print(f"x += 3 -> {x}")
x -= 2; print(f"x -= 2 -> {x}")
x *= 4; print(f"x *= 4 -> {x}")
x /= 2; print(f"x /= 2 -> {x}")
x %= 3; print(f"x %= 3 -> {x}")

def bitwise_operators(a, b):


print("\nBitwise Operators:")
print(f"{a} & {b} -> {a & b}")
print(f"{a} | {b} -> {a | b}")
print(f"{a} ^ {b} -> {a ^ b}")
print(f"~{a} -> {~a}")
print(f"{a} << 2 -> {a << 2}")
print(f"{a} >> 2 -> {a >> 2}")

while True:
print("\n========= OPERATOR MENU =========")
print("0. Exit")
print("1. Arithmetic Operators")
print("2. Comparison Operators")
print("3. Logical Operators")
print("4. Assignment Operators")
print("5. Bitwise Operators")

try:
choice = int(input("Enter your choice: "))
except ValueError:
print("Please enter a number.")
continue

if choice == 0:
print("*** THE END ***")
break

if choice in (1, 2, 3, 5):


try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
except ValueError:
print("Invalid input. Use integers.")

if choice == 1:
arithmetic_operators(a, b)
elif choice == 2:
comparison_operators(a, b)
elif choice == 3:
logical_operators(a, b)
elif choice == 4:
assignment_operators()
elif choice == 5:
bitwise_operators(a, b)
else:
print("Invalid choice.")
OUTPUT:
========= OPERATOR MENU =========
0. Exit
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
Enter your choice: 1
Enter first number: 40
Enter second number: 27

Arithmetic Operators:
40 + 27 = 67
40 - 27 = 13
40 * 27 = 1080
40 / 27 = 1.4814814814814814
40 % 27 = 13
40 ** 27 = 18014398509481984000000000000000000000000000
40 // 27 = 1

========= OPERATOR MENU =========


0. Exit
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
Enter your choice: 2
Enter first number: 40
Enter second number: 27

Comparison Operators:
40 == 27 -> False
40 != 27 -> True
40 > 27 -> True
40 < 27 -> False
40 >= 27 -> True
40 <= 27 -> False
Q7: Create a python program to generate random numbers:

CODE:
import random

def generate_random_number():
while True:
try:
lower = int(input("Enter the lower bound: "))
upper = int(input("Enter the upper bound: "))
if lower > upper:
print("Lower bound must be less than or equal to
upper bound.")
else:
number = [Link](lower, upper)
print(f" Your random number between {lower} and
{upper} is: {number}")
break
except ValueError:
print("Please enter valid whole numbers.")

generate_random_number()

OUTPUT:
Enter the lower bound: 1

Enter the upper bound: 0

Lower bound must be less than or equal to upper bound.

Enter the lower bound: 1

Enter the upper bound: 15

A random number between 1 and 15 is: 12


Q8: Create a python program to read a text file line by line:

CODE:
print('function to read a text_file line by line:\n\t')

def read_file_linewise():
try:
f = open('[Link]', 'r')
while True:
s=[Link]()
print(s,end='')
if len(s)==0:
break
[Link]()
except:
print('error!')

read_file_linewise()

FILE:

OUTPUT:
function to read a text_file line by line:

Hello!
My name is Upraj
Q9: Create a python program to read a text file word by word:

CODE:
print('function to read a text_file word by word:\n\t')

def read_file_wordwise():
try:
f = open('[Link]', 'r')
s=[Link]()
l=[Link]()
for i in l:
print(i)
[Link]()
except:
print('error!')

read_file_wordwise()

FILE:

OUTPUT:
function to read a text_file word by word:

Hello!
My
name
is
Upraj.
Q10: Creating a python program to copy particular lines of a text file into another text file:

CODE:

def copy_lines_by_rollnos(source_file, target_file, rollnos):

try:
src = open(source_file, 'r')
tgt = open(target_file, 'w')

matched = False
for line in src:
for rollno in rollnos:
if rollno in line:
[Link](line)
matched = True
break

if matched:
print(f"Lines with roll numbers {rollnos} copied to
'{target_file}'.")
else:
print("No matching lines found for the given roll
numbers.")

[Link]()
[Link]()

except:
print("Error")

rollno_list = []
print("Enter roll numbers one by one. Type 'done' to finish:")

while True:
roll = input("Enter roll number: ")
if [Link]() == 'done':
break
rollno_list.append([Link]())

source_path = "[Link]"
target_path = "matched_rollno.txt"

copy_lines_by_rollnos(source_path, target_path, rollno_list)


FILE:

OUTPUT:

Enter roll numbers one by one. Type 'done' to finish:


Enter roll number: 1
Enter roll number: 2
Enter roll number: 3
Enter roll number: 4
Enter roll number: done
Lines with roll numbers ['1', '2', '3', '4'] copied to
'matched_rollno.txt'.
Q11: Create a python program to create and search records in binary file:

CODE:
import pickle

def add_record(filename):
try:
f = open(filename, 'ab')
roll = input("Enter Roll Number: ")
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
record = {'roll': roll, 'name': name, 'marks': marks}
[Link](record, f)
[Link]()
print("Record added successfully.\n")
except:
print("Error")

def search_record(filename):
try:
f = open(filename, 'rb')
roll_to_search = input("Enter Roll Number to search: ")
found = False
while True:
try:
record = [Link](f)
if record['roll'] == roll_to_search:
print("Record Found:")
print(f"Roll No: {record['roll']}, Name:
{record['name']}, Marks: {record['marks']}\n")
found = True
break
except EOFError:
break
[Link]()
if not found:
print("Record not found.\n")
except:
print("Error")

def menu():
filename = "student_records.dat"
while True:
print("===== Student Record Menu =====")
print("1. Add Record")
print("2. Search Record")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
add_record(filename)

elif choice == '2':


search_record(filename)
elif choice == '3':
print("Exiting program. Goodbye!")
break

else:
print("Invalid choice. Please try again.\n")

menu()

OUTPUT:
===== Student Record Menu =====
1. Add Record
2. Search Record
3. Exit
Enter your choice (1-3): 1
Enter Roll Number: 1
Enter Name: Upraj
Enter Marks: 94
Record added successfully.

===== Student Record Menu =====


1. Add Record
2. Search Record
3. Exit
Enter your choice (1-3): 2
Enter Roll Number to search: 1
Record Found:
Roll No: 1, Name: Upraj, Marks: 94.0

===== Student Record Menu =====


1. Add Record
2. Search Record
3. Exit
Enter your choice (1-3): 2
Enter Roll Number to search: 2
Record not found.
Q12: Create a python program to create and modify records in binary file:
CODE:
import pickle
def add_record(filename):
try:
with open(filename, 'ab') as f:
roll = input("Enter Roll Number: ")
name = input("Enter Name: ")
percentage = float(input("Enter Percentage: "))
record = {'roll': roll, 'name': name, 'percentage':
percentage}
[Link](record, f)
print("Record added successfully.\n")
except :
print("Error")

def modify_record(filename):
try:
records = []
found = False

with open(filename, 'rb') as f:


while True:
try:
record = [Link](f)
[Link](record)
except:
break

roll_to_modify = input("Enter Roll Number to modify: ")

for i in range(len(records)):
if records[i]['roll'] == roll_to_modify:
print("Current Record:")
print(f"Roll No: {records[i]['roll']}, Name:
{records[i]['name']}, Percentage: {records[i]['percentage']}")
records[i]['name'] = input("Enter New Name: ")
records[i]['percentage'] = float(input("Enter New
Percentage: "))
found = True
break

if found:
with open(filename, 'wb') as f:
for rec in records:
[Link](rec, f)
print("Record modified successfully.\n")
else:
print("Record not found.\n")
except:
print("Error:")

def menu():
filename = "student_records.dat"
while True:
print("===== Student Record Menu =====")
print("1. Add Record")
print("2. Modify Record")
print("3. Exit")
choice = input("Enter your choice (1-3): ")

if choice == '1':
add_record(filename)
elif choice == '2':
modify_record(filename)
elif choice == '3':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.\n")
menu()

OUTPUT:

===== Student Record Menu =====


1. Add Record
2. Modify Record
3. Exit
Enter your choice (1-3): 1
Enter Roll Number: 1
Enter Name: Upraj
Enter Percentage: 98
Record added successfully.

===== Student Record Menu =====


1. Add Record
2. Modify Record
3. Exit
Enter your choice (1-3): 2
Enter Roll Number to modify: 1
Current Record:
Roll No: 1, Name: Upraj, Percentage: 98.0
Enter New Name: Upraj
Enter New Percentage: 96.7
Record modified successfully.
Q13: Create a python program to create and search employee’s record in csv file:

CODE:

import csv

def add_employee(filename):
try:
f = open(filename, 'a', newline='')
writer = [Link](f)
emp_id = input("Enter Employee ID: ")
name = input("Enter Name: ")
department = input("Enter Department: ")
salary = float(input("Enter Salary: "))
[Link]([emp_id, name, department, salary])
[Link]()
print("Employee record added successfully.\n")

except :
print("Error")

def search_employee(filename):
try:
emp_id_to_search = input("Enter Employee ID to search: ")
found = False
f = open(filename, 'r')
reader = [Link](f)
for row in reader:
if row and row[0] == emp_id_to_search:
print("Employee Found:")
print(f"ID: {row[0]}, Name: {row[1]}, Department:
{row[2]}, Salary: {row[3]}\n")
found = True
break
[Link]()
if not found:
print("Employee not found.\n")

except :
print("Error")
def menu():
filename = "employee_records.csv"
while True:
print("===== Employee Record Menu =====")
print("1. Add Employee")
print("2. Search Employee")
print("3. Exit")
choice = input("Enter your choice (1-3): ")

if choice == '1':
add_employee(filename)

elif choice == '2':


search_employee(filename)

elif choice == '3':


print("Exiting program. Goodbye!")
break

else:
print("Invalid choice. Please try again.\n")

menu()
OUTPUT:
===== Employee Record Menu =====

1. Add Employee

2. Search Employee

3. Exit

Enter your choice (1-3): 1


Enter Employee ID: 1
Enter Name: Upraj
Enter Department: 10
Enter Salary: 67000
Employee record added successfully.

===== Employee Record Menu =====

1. Add Employee

2. Search Employee

3. Exit
Enter your choice (1-3): 2
Enter Employee ID to search: 1
Employee Found:
ID: 1, Name: Upraj, Department: 10, Salary: 10000.0

===== Employee Record Menu =====

1. Add Employee

2. Search Employee
3. Exit

Enter your choice (1-3): 2


Enter Employee ID to search: 3
Employee not found.
Q14: Create a python program to implement stack operations(LIST):

CODE:
stack = []
top = -1

def push():
global top
item = input("Enter item to push: ")
[Link](item)
top += 1
print(f"'{item}' pushed. Top is now at index {top}.")

def pop():
global top
if top == -1:
print("Stack Underflow")
else:
item = [Link]()
print(f"'{item}' popped. Top was at index {top}.")
top -= 1

def peek():
if top == -1:
print("Stack is empty. No top element.")
else:
print(f"Top element is: {stack[top]}")

def display():
if top == -1:
print("Stack is empty.")
else:
print("Stack contents from bottom to top:")
for i in range(top + 1):
print(f"Index {i}: {stack[i]}")

def menu():
while True:
print("\n--- Stack Operations Menu ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to
5.")
menu()

OUTPUT:
--- Stack Operations Menu ---
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 1
Enter item to push: 3
'3' pushed. Top is now at index 2.

--- Stack Operations Menu ---


1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 1
Enter item to push: 4
'4' pushed. Top is now at index 3.

--- Stack Operations Menu ---


1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 4
Stack contents from bottom to top:
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Q15: Create a python program to implement stack operations(DICTIONARY):

CODE:

stack = {}
top = -1

def push():
global top
item = input("Enter item to push: ")
top += 1
stack[top] = item
print(f"'{item}' pushed at position {top}.")

def pop():
global top
if top == -1:
print("Stack Underflow! Cannot pop from empty stack.")
else:
item = [Link](top)
print(f"'{item}' popped from position {top}.")
top -= 1

def peek():
if top == -1:
print("Stack is empty. No top element.")
else:
print(f"Top element is: {stack[top]}")

def display():
if top == -1:
print("Stack is empty.")
else:
print("Stack contents from bottom to top:")
for i in range(top + 1):
print(f"Position {i}: {stack[i]}")

def menu():
while True:
print("\n--- Stack Operations Menu (Dictionary) ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to
5.")

menu()

OUTPUT:

--- Stack Operations Menu (Dictionary) ---


1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 1
Enter item to push: 1
'1' pushed at position 0.

--- Stack Operations Menu (Dictionary) ---


1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 4
Stack contents from bottom to top:
Position 0: 1

--- Stack Operations Menu (Dictionary) ---


1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice (1-5): 2
'1' popped from position 0.
Q16:Create a python program to integrate MYSQL with Python:

CODE:

import pymysql as x
def create_table():
try:

d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q='create table stu(rollno int primary key,name
varchar(20),maths int,eng int,cs int);'
[Link](q)
[Link]()
[Link]()
[Link]()
print('table stu created')
except:
print('table stu already created')
def insert_record(b, c, g, e, f):
try:
d = [Link](host='localhost', user='root', passwd='usb',
db='xii')
cur = [Link]()
query = "INSERT INTO stu (rollno, name, maths, eng, cs)
VALUES (%s, %s, %s, %s, %s)"
[Link](query, (b, c, g, e, f))
[Link]()
[Link]()
[Link]()
print("Record added successfully!")
except :
print(f"Error ")
def display_table():
try:

d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q='select*from stu;'
[Link](q)
r=[Link]()
for i in r:
print(i)
[Link]
[Link]
except:
print('error')
def delete_record(h,i):
try:
d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q = f'delete from stu WHERE {h} = %s'
[Link](q, (i,))
[Link]()
[Link]()
[Link]()
print(f'row deleted where {h} is {i}')
except:
print('ERROR')
def update_record(j,k,l,m):
try:

d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q = f'update stu set {j}=%s where {l}=%s'
[Link](q, (k, m))
[Link]()
[Link]()
[Link]()
except:
print('ERROR')
def search_Record(n,o):
try:

d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q=f'select*from stu where {n}=%s;'
[Link](q, (o,))
r=[Link]()
for i in r:
print(i)
[Link]
[Link]
except:
print('error')
def sort_table(y,z):
try:
z=[Link]()

d=[Link](host='localhost',user='root',passwd='usb',db='xii')
cur=[Link]()
q=f'select*from stu ORDER BY {y} {z};'
[Link](q)
r=[Link]()
for i in r:
print(i)
[Link]()
[Link]()
except:
print('error')
while True:
print('\n\tMENU')
print('\n\[Link]')
print('\n\[Link] table')
print('\n\[Link] record')
print('\n\[Link] table')
print('\n\[Link] row')
print('\n\[Link] row')
print('\n\[Link] row')
print('\n\[Link] table\n\t')
a=int(input('enter num'))
if a not in (1,2,3,4,5,6,7):
print('\n\t***THE END***')
break
if a==1:
create_table()
if a==2:
b = int(input('Enter unique roll no: '))
c = input('Enter name: ')
g = int(input('Marks in Maths: '))
e = int(input('Marks in English: '))
f = int(input('Marks in CS: '))
insert_record(b,c,g,e,f)
if a==3:
print('\n\t***TABLE***\n')
display_table()
if a==4:
h=input('column from which u want to pass parameter')
i=input('value of which u want to delete')
i=eval(i)
delete_record(h,i)
if a==5:
j=input('name of column where u want to change the value')
k=input('value u want to change it into')
l=input('column after where clause which acts as a reference
point')
m=input('value of this column')
if [Link]():
k=eval(k)
if [Link]():
m=eval(m)
update_record(j,k,l,m)
print('value changed successfully!')
if a==6:
n=input('column name from where u want to search records')
o=input('its value')
search_Record(n,o)
print(f'record(s) where {n} is {o}')
if a==7:
y=input('enter column by which u want to sort')
z=input('ascending or descending (ASC/DESC)')
z=[Link]()
if z in ('ASC','DESC'):
sort_table(y,z)
print(f'sorted by column-{y}')
else:
print(f'{z} should be ASC or DESC')

OUTPUT:

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num2
Enter unique roll no: 4
Enter name: Atharv
Marks in Maths: 99
Marks in English: 82
Marks in CS: 33
Record added successfully!

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num:3

***TABLE***

(1, 'Upraj', 99, 99, 99)


(2, 'Tanmay', 67, 89, 99)
(3, 'Ujjwal', 88, 66, 84)
(4, 'Atharv', 99, 82, 33)
(5, 'Kunal', 99, 99, 88)
====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num:4
column from which u want to pass parameter:rollno
value of which u want to delete:5
row deleted where rollno is 5

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num:5
name of column where u want to change the value:rollno
value u want to change it into:5
column after where clause which acts as a reference point:rollno
value of this column:4
value changed successfully!

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table
enter num:3

***TABLE***

(1, 'Upraj', 99, 99, 99)


(2, 'Tanmay', 67, 89, 99)
(3, 'Ujjwal', 88, 66, 84)
(5, 'Atharv', 99, 82, 33) #value changed from 4->5

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num6
column name from where u want to search records:rollno
its value:1
(1, 'Upraj', 99, 99, 99)
record(s) where rollno is 1

====MENU=====
[Link]
[Link] table
[Link] record
[Link] table
[Link] row
[Link] row
[Link] row
[Link] table

enter num7
enter column by which u want to sort:rollno
ascending or descending (ASC/DESC):desc
(5, 'Atharv', 99, 82, 33)
(3, 'Ujjwal', 88, 66, 84)
(2, 'Tanmay', 67, 89, 99)
(1, 'Upraj', 99, 99, 99)
sorted by column-rollno
Q17:SQL commands exercise-1:

TABLE:
+-------+-----------+-----------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-----------+-----------+------+------------+---------+------+--------+
| 8369 | smith | clerk | 8902 | 1990-12-18 | 792 | NULL | 20 |
| 8499 | anya | salesman | 8698 | 1991-02-20 | 1600 | 300 | 30 |
| 8521 | seth | salesman | 8698 | 1991-02-22 | 1250 | 500 | 30 |
| 8566 | mahadevan | manager | 8839 | 1991-04-02 | 2955.15 | NULL | 20 |
| 8654 | momin | salesman | 8698 | 1991-09-28 | 1250 | 1400 | 30 |
| 8698 | bina | manager | 8839 | 1991-05-01 | 2821.5 | NULL | 30 |
| 8839 | amir | president | NULL | 1991-11-18 | 4950 | NULL | 10 |
| 8844 | kuldeep | salesman | 8698 | 1991-09-08 | 1500 | 0 | 10 |
| 8882 | shiavansh | manager | 8839 | 1991-06-09 | 2425.5 | NULL | 10 |
| 8886 | anoop | clerk | 8888 | 1993-01-12 | 1089 | NULL | 20 |
| 8888 | scott | analyst | 8566 | 1992-12-09 | 2970 | NULL | 20 |
| 8900 | jatin | clerk | 8698 | 1991-12-03 | 940.5 | NULL | 30 |
| 8902 | fakir | analyst | 8566 | 1991-12-03 | 2970 | NULL | 20 |
| 8934 | mita | clerk | 8882 | 1992-01-23 | 1287 | NULL | 10 |
+-------+-----------+-----------+------+------------+---------+------+--------+
14 rows in set (0.03 sec)

Q1:Write a query to display the name of employee who is having ‘L’ in their name:

Solution:
mysql> SELECT ename FROM emp WHERE ename like '%l%';
+---------+
| ename |
+---------+
| kuldeep |
+---------+
1 row in set (0.01 sec)

Q2:List the details of all employees whose annual salary is between 25000->40000:

Solution:
mysql> SELECT*FROM emp WHERE sal*12 BETWEEN 25000 AND 40000;
+-------+-----------+---------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-----------+---------+------+------------+---------+------+--------+
| 8566 | mahadevan | manager | 8839 | 1991-04-02 | 2955.15 | NULL | 20 |
| 8698 | bina | manager | 8839 | 1991-05-01 | 2821.5 | NULL | 30 |
| 8882 | shiavansh | manager | 8839 | 1991-06-09 | 2425.5 | NULL | 10 |
| 8888 | scott | analyst | 8566 | 1992-12-09 | 2970 | NULL | 20 |
| 8902 | fakir | analyst | 8566 | 1991-12-03 | 2970 | NULL | 20 |
+-------+-----------+---------+------+------------+---------+------+--------+
5 rows in set (0.00 sec)
Q3:Write a query to display employee name. salary and department number who are not getting
commission from the above table:

Solution:
mysql> SELECT ename,sal,deptno FROM emp WHERE comm is null or comm=0;
+-----------+---------+--------+
| ename | sal | deptno |
+-----------+---------+--------+
| smith | 792 | 20 |
| mahadevan | 2955.15 | 20 |
| bina | 2821.5 | 30 |
| amir | 4950 | 10 |
| kuldeep | 1500 | 10 |
| shiavansh | 2425.5 | 10 |
| anoop | 1089 | 20 |
| scott | 2970 | 20 |
| jatin | 940.5 | 30 |
| fakir | 2970 | 20 |
| mita | 1287 | 10 |
+-----------+---------+--------+
11 rows in set (0.00 sec)

Q4:List the details of employees who earn more commission than their salary:

Solution:
mysql> select*from emp where comm>sal;
+-------+-------+----------+------+------------+------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-------+----------+------+------------+------+------+--------+
| 8654 | momin | salesman | 8698 | 1991-09-28 | 1250 | 1400 | 30 |
+-------+-------+----------+------+------------+------+------+--------+
1 row in set (0.00 sec)

Q5:Write a query to display the name of employee whose name contains ‘A’ as third alphabet:

Solution:
mysql> select ename from emp where ename like '_a%';
+-----------+
| ename |
+-----------+
| mahadevan |
| jatin |
| fakir |
+-----------+
3 rows in set (0.00 sec)
Q18:SQL command exercise-2:

TABLE:
+-----+---------+------+------------+------------+---------+
| VID | Name | Age | Dose1 | Dose2 | City |
+-----+---------+------+------------+------------+---------+
| 101 | Jenny | 27 | 2021-12-25 | 2022-01-31 | Delhi |
| 102 | Harjot | 55 | 2021-07-14 | 2021-10-14 | Mumbai |
| 103 | Srikant | 43 | 2021-04-18 | 2022-07-20 | Delhi |
| 104 | Gazala | 75 | 2021-07-31 | NULL | Kolkata |
| 105 | Shiksha | 32 | 2022-01-01 | NULL | Mumbai |
+-----+---------+------+------------+------------+---------+
5 rows in set (0.00 sec)

Q1:Display name and age from table whose 2nd dose has been given and age more than 40:

Solution:
mysql> select name,age from vaccination where dose2 is not NULL and
age>40;
+---------+------+
| name | age |
+---------+------+
| Harjot | 55 |
| Srikant | 43 |
+---------+------+
2 rows in set (0.00 sec)

Q2:display all the city where vaccination has been given:

Solution:
mysql> select DISTINCT city from vaccination;
+---------+
| city |
+---------+
| Delhi |
| Mumbai |
| Kolkata |
+---------+
3 rows in set (0.00 sec)
Q3:display when the last 1st dose was given and when the first 2nd dose was given:

Solution:
mysql> select max(dose1),min(dose2) from vaccination;
+------------+------------+
| max(dose1) | min(dose2) |
+------------+------------+
| 2022-01-01 | 2021-10-14 |
+------------+------------+
1 row in set (0.01 sec)

Q19:SQL commands exercise-3:

TABLE:
+---------+---------------+-----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+---------------+-----------+-------------+----------------+--------------+
| 1 | Hindi_movie | musical | 2018-04-23 | 124500 | 130000 |
| 2 | Tamil_movie | action | 2016-05-17 | 112000 | 118000 |
| 3 | English_movie | horror | 2017-08-06 | 245000 | 360000 |
| 4 | Bengali_movie | adventure | 2017-01-04 | 72000 | 100000 |
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+---------------+-----------+-------------+----------------+--------------+
5 rows in set (0.00 sec)

Q1:Find the net profit of each movie showing its ID,name and net profit:

Solution:
mysql> select movieID,moviename,buisnesscost-productioncost as 'Net_profit'
from movie;
+---------+---------------+------------+
| movieID | moviename | Net_profit |
+---------+---------------+------------+
| 1 | Hindi_movie | 5500 |
| 2 | Tamil_movie | 6000 |
| 3 | English_movie | 115000 |
| 4 | Bengali_movie | 28000 |
| 5 | Telugu_movie | NULL |
+---------+---------------+------------+
5 rows in set (0.01 sec)
Q2:List details of all movies which have not been released yet:

Solution:
mysql> select*From movie where releasedate is null;
+---------+--------------+----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+--------------+----------+-------------+----------------+--------------+
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+--------------+----------+-------------+----------------+--------------+
1 row in set (0.01 sec)

Q3:List movieID,name and cost of all movies with product cost greater than 10000 and less than
100000:

Solution:
mysql> select movieID,moviename,productioncost from movie where productioncost
BETWEEN 10000 AND 100000;
+---------+---------------+----------------+
| movieID | moviename | productioncost |
+---------+---------------+----------------+
| 4 | Bengali_movie | 72000 |
| 5 | Telugu_movie | 100000 |
+---------+---------------+----------------+
2 rows in set (0.00 sec)

Q4:List details of all movies which fall in the category of action and horror:

Solution:
mysql> select*from movie where category in ('horror','action');
+---------+---------------+----------+-------------+----------------+--------------+
| movieID | movieName | category | releaseDate | productionCost | buisnessCost |
+---------+---------------+----------+-------------+----------------+--------------+
| 2 | Tamil_movie | action | 2016-05-17 | 112000 | 118000 |
| 3 | English_movie | horror | 2017-08-06 | 245000 | 360000 |
| 5 | Telugu_movie | action | NULL | 100000 | NULL |
+---------+---------------+----------+-------------+----------------+--------------+
3 rows in set (0.00 sec)
Q20:SQL command exercise-4

TABLE:
+-----------+-------+---------+------------+--------+-------------+--------+
| studentNo | class | name | game | grade1 | SUPW | grade2 |
+-----------+-------+---------+------------+--------+-------------+--------+
| 10 | 7 | sameer | cricket | B | photography | A |
| 11 | 8 | sujit | tennis | A | gardening | C |
| 12 | 7 | kamal | swimming | B | photography | B |
| 13 | 7 | veena | tennis | C | cooking | A |
| 14 | 9 | archana | basketball | A | literature | A |
+-----------+-------+---------+------------+--------+-------------+--------+
5 rows in set (0.00 sec)

Q1:Display the names of the students who are getting a grade ‘C’ in either game or SUPW:

Solution:
mysql> select name from student where grade1='C' or grade2='C';
+-------+
| name |
+-------+
| sujit |
| veena |
+-------+
2 rows in set (0.00 sec)

Q2:Display the different games offered in the school:

Solution:
mysql> Select Distinct game from student;
+------------+
| game |
+------------+
| cricket |
| tennis |
| swimming |
| basketball |
+------------+
4 rows in set (0.00 sec)

Q3:Display name and SUPW taken by students whose name starts with ‘A’:
Solution:
mysql> select name,supw from student where name like 'a%';
+---------+------------+
| name | supw |
+---------+------------+
| archana | literature |
+---------+------------+
1 row in set (0.00 sec)

Q21:SQL commands exercise-5

TABLE:
+-----+----------+------+------------+------------+--------+------+
| ID | name | age | department | dateOfjoin | salary | sex |
+-----+----------+------+------------+------------+--------+------+
| 101 | jugal | 34 | computer | 1997-01-10 | 12000 | M |
| 102 | sharmila | 31 | history | 1998-03-24 | 20000 | F |
| 103 | sandeep | 32 | maths | 1996-12-12 | 30000 | M |
| 104 | sangeeta | 35 | history | 1999-07-01 | 40000 | F |
| 105 | rakesh | 42 | maths | 1997-09-05 | 35000 | M |
+-----+----------+------+------------+------------+--------+------+
5 rows in set (0.00 sec)

Q1:Show all info about teachers of history department:

Solution:
mysql> select*from teacher where department='history';
+-----+----------+------+------------+------------+--------+------+
| ID | name | age | department | dateOfjoin | salary | sex |
+-----+----------+------+------------+------------+--------+------+
| 102 | sharmila | 31 | history | 1998-03-24 | 20000 | F |
| 104 | sangeeta | 35 | history | 1999-07-01 | 40000 | F |
+-----+----------+------+------------+------------+--------+------+
2 rows in set (0.00 sec)

Q2:Name of female teacher with salary more than 30000:

Solution:
mysql> select name from teacher where sex='F' and salary>30000;
+----------+
| name |
+----------+
| sangeeta |
+----------+
1 row in set (0.00 sec)
Q3:List names of all teacher with their date of joining in ascending order:

Solution:
mysql> select name from teacher order by dateofjoin;
+----------+
| name |
+----------+
| sandeep |
| jugal |
| rakesh |
| sharmila |
| sangeeta |
+----------+
5 rows in set (0.01 sec)
BIBLIOGRAPHY
This project draws upon the foundational concepts and examples presented in
Computer Science with Python for Class XII by Sumita Arora, published by
Dhanpat Rai & Co. in 2025.

You might also like