You are on page 1of 68

[DOCUMENT TITLE]

COMPUTER
SCIENCE
JOURNAL

Name-Nidhi Salian
Class- XII S2
Academic year-2023-24
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
SQL Queries

1. Count & display the total number of Managers in the STAFF table.

2. Display Name, StNo, and BS of all Managers who get salary more than Rs 40000

3. Display the total no. of Desgn listed in STAFF table.

4. Display details of Staff getting highest salary

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
5. Display details of Staff whose name start with ‘A’

6. Display details of Staff whose name have the letter ‘a’ in it

7. Display details of Staff whose name has a ‘y’ in the third place.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
8. Display Name, StNo, BS, allowance (10% of BS) of all Salesmen from the STAFF table
where allowance is given as 10% of BS

9. Display Name, StNo, BS, Commission (Comm), Net Salary (NS) (BS + Comm), department
and city of each salesman, where Comm is calculated as 10% of BS & NS is Basic + Comm

10. Display details of salesmen with highest allowance (which is 10% of BS) from the STAFF
table.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
11. Display details of employees belonging to ‘Operation’ department

12. Display details of those employees and their department who work in dept no. ’d02’

13. Display details of those employees who get a salary greater than equal to 50000 or less than
equals to 100000

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
14. Display number of employees working in each department except for those working in HRD dept.

15. Display the average amount of the salary received by the salesmen & the Managers.

16. Display average salary for all those employees who stay in Delhi.

17. Display all the designation listed in the staff table and the number of employees working
under that designation. List only those records where the number of employees working is
less than 2.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
18. Create a new table named: salesmannew with details of all salesmen copied from the staff
table.

19. Increment salary of all salesmen by 10% in the staff table.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
20. Create a view named: newview which shows details of all staff getting BS between 40000 and
100000.

21. Write a query to display details of all staff with staff names and designation listed in capital
letters.

22. Display details of all staff members in ascending order of their names.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
23. Display details of all staff members in descending order of their salary.

24. Show designation wise average and sum of salary of staff members listed in ascending order
of their designation.

25. Delete details of all staff members who are not ‘salesman’

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
26. Add a new column age to the staff table with the default age as 22.

27. Modify the age column in staff table to make it float type.

28. Drop the column age & stno.

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
29. Rename the attribute named city in department table to Location with size 25

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Python Journal questions

Q1) Write a menu driven program to perform the following options


i. To find the factorial of an entered number
ii. To print the Fibonacci Series up to N
iii. Exit
Code:

#Q1
def factorial(n): #Factorial of n
p=1
for i in range(1,n+1):
p=p*i
print('Factorial of',n,'=',p)
def fibonacci(N): #Fibonacci series upto N
s=0
f,t=1,1
while(t<=N):
print(t, end=' ')
f=s
s=t
t=f+s
print()
while(1):
print('\t','Choose a Number','\t')
print('1','\t','To find factorial of a given number')
print('2','\t','Print Fibonacci series upto N')
print('3','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:
number=int(input("Enter a number: "))
factorial(number)

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
elif no==2:
number=int(input("Enter a number: "))
fibonacci(number)
elif no==3:
print("You choose to exit")
break
else:
print("Invalid Choice")
print("Try again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q2) Write a Menu driven program with the following choices.

1. To find the vowels and consonants in a given string.


2. Check if a given String is Palindrome or not.
3. To count the total no. of words in the given string.
4. Exit
Code:
#Q2
def vowcon(s): #Count no.of vowels and consonants in string
vcount=0

ccount=0
V=['A','a','E','e','I','i','O','o','U','u']
C='bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
for i in s:
if i in V:
vcount+=1
elif i in C:
ccount+=1
else:
if vcount==0 and ccount==0:
print("No vowels or consonants found in",s)
else:
print("Total no of vowels in",s,"=",vcount)
print("Total no of consonants in",s,"=",ccount)

def palindrome(s): #check if string is palindrome or not

rs=s[::-1]
if s==rs:
print(s,'is a palindrome')
else:

print(s,'is not a palindrome')

def words(s): #count no. of words in a string

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
lst=s.split()
count=len(lst)
print("No.of words in",s,'=',count)

while(1):
print('\t','Choose a Number','\t')
print('1','\t','To find the vowels and consonants in a given string.')
print('2','\t','Check if a given String is Palindrome or not.')
print('3','\t','To count the total no. of words in the given string.')
print('4','\t','Exit')
no=int(input("Choose a Number: "))

if no==1:
st=input("Enter a string: ")
vowcon(st)
elif no==2:

st=input("Enter a string: ")


palindrome(st)
elif no==3:
st=input("Enter a string: ")

words(st)
elif no==4:
print("You choose to exit")
break

else:
print("Invalid Choice")
print("Try again")

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q3) Write a menu driven program with the following options:
1. To print the number of occurrences of a sub string in an accepted string.
2. To print an accepted string in reverse order.

3. To find the longest word & print its position.


4. Exit

Code:
#Q3
def substring_hunting(sub): #To find number of occurrences of substring
lst=s.split()
count=0

for i in range(len(lst)):
if sub==lst[i]:
count+=1
else:
if count==0:
print(sub,'is not in string','"',s,'"')
else:
print("No. of occurences of",sub,'=',count)

def reverse_str(s): #To print reverse of string


ws=''
for i in range(len(s)):
ws=ws+s[(-1)*(i+1)]
print('Original string=',s)
print('Reverse string=',ws)

def longword(s): # to find longest word and its position


lst=s.split()
max=0
for i in range(len(lst)):

if len(lst[i])>max:
max=len(lst[i])
pos=i

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print('The longest word is,', lst[pos])
print("Position of",lst[pos],"is",pos)

while(1):
print('\t','Choose a Number','\t')
print('1','\t','To print the number of occurrences of a sub string in an accepted string.')
print('2','\t','To print an accepted string in reverse order.')
print('3','\t','To find the longest word & print its position.')
print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:

s=input("Enter a string: ")


su=input("Enter substring: ")
substring_hunting(su)
elif no==2:

st=input("Enter a string: ")


reverse_str(st)
elif no==3:
st=input("Enter a string: ")

longword(st)
elif no==4:
print("You choose to exit")
break

else:
print("Invalid Choice")
print("Try again")

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q4) Write a menu driven program with the following options:
i. To accept a set of numbers & store them into a list
ii. To accept a no & find its position in the list

iii. To accept a no & delete it from the list


iv. Exit
Code:
#Q4
def lst(): #create a list
l=[]
ans='y'
while ans=='y' or ans=='Y':

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


l.append(n)
ans=input('Do you want to continue Y/N: ')
print('List Created: ',l)

return l
def position(no): #To tell the position of the element
for i in range(len(l)):
if no==l[i]:

pos=i
print(no,'is at position',i,'in',l)
break
else:

print(no,'not in list')
def acc_del(no): #To delete an element
for i in range(len(l)):
if no==l[i]:

l.remove(no)
print('New list: ',l)
break
else:

print(no,'not in list')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
while(1):
print('\t','Choose a Number','\t')
print('1','\t','To accept a set of numbers & store them into a list')

print('2','\t','To accept a no & find its position in the list')


print('3','\t','To accept a no & delete it from the list')
print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:
l=lst()
elif no==2:
n=int(input("Enter a number: "))

position(n)
elif no==3:
n=int(input("Enter a number: "))
acc_del(n)

elif no==4:
print("You choose to exit")
break
else:

print("Invalid Choice")
print("Try again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q5) Write a menu driven program with the following options:
i. To accept a set of numbers & create a Tuple
ii. To find the Lowest & highest Number from the Tuple (without using any in-built function)

iii. To find sum & average of all elements in the Tuple (without using any in-built function)
iv. Exit
Code:
#Q5
def tup(): #Create a tuple
ans='y'
l=[]
while ans=='y' or ans=='Y':

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


l.append(n)
ans=input("Do you want to continue Y/N: ")
t=tuple(l)

print("The tuple formed: ",t)


return t
def max_min(): #To find out maximum & minimum
mx=t[0]

mn=t[0]
for i in range(len(t)):
if t[i]>mx:
mx=t[i]

if t[i]<mn:
mn=t[i]
print('The highest number in tuple: ',mx)
print('The lowest number in tuple: ',mn)

def sum_avg(): #To find sum and average


s=0
for i in t:
s+=i

print("The sum of all the elements in the tuple =",s)


av=s/len(t)

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print("The average of all the elements in the tuple =",av)
while(1):
print('\t','Choose a Number','\t')

print('1','\t','To accept a set of numbers & create a Tuple')


print('2','\t','To find the Lowest & highest Number from the Tuple')
print('3','\t','To find sum & average of all elements in the Tuple')
print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:
t=tup()
elif no==2:

max_min()
elif no==3:
sum_avg()
elif no==4:

print("You choose to exit")


break
else:
print("Invalid Choice")

print("Try again")

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q6) Write a menu driven Python program with the following options:
1. To create a dictionary by accepting Name and marks of N students. (Use name as key & marks as
value.)
2. Display the contents of the dictionary. If it is empty, print appropriate message.
3. To check whether a given name exists in the dictionary, if present print his/her marks.

4. Exit
Code:
#Q6
while(1):

print('\t','Choose a Number','\t')
print('1','\t','To create a dictionary by accepting Name and marks of N students.')
print('2','\t','Display the contents of the dictionary.')
print('3','\t','To check whether a given name exists in the dictionary')

print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1: #Creating a dictionary
d={}

found=0
N=int(input("Enter no. of students: "))
for i in range(N):
name=input("Enter name of student: ")

mks=float(input("Enter marks of student: "))


d[name]=mks
found=1
print("Dictionary created")
elif no==2: #Display the contents of dictionary
if found!=0:
print('Name','\t','Marks')
for key in d:

print(f'{key}\t{d[key]}')
else:
print("No item in dictionary")
elif no==3: #Check if name exists in dictionary

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
nm=input("Enter name to be searched: ")
for k in d:
if nm==k:

print(f'Marks of {nm} is {d[k]}')


break
else:
print(f'{nm} not in dictionary')
elif no==4:
print("You choose to exit")
break
else:

print("Invalid Choice")
print("Try again")

Output:

Case 1

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Case 2

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q7) Write a program to write the following lines of text into a file, named exprsn.txt. Read this text
file line by line and display each word separated by a - # symbol.
‘life is an adventure, like a roller coaster. That explains the ups and
downs in life. Often, when we think we are at the end of something, we are
actually at the beginning of something else.’

Code:
#Q7
fh=open('exprsn .txt','w') #write in file
fh.writelines('life is an adventure, like a roller coaster. That explains the ups and\n')
fh.writelines('downs in life. Often, when we think we are at the end of something, we are\n')
fh.writelines('actually at the beginning of something else.')
print("Content written in file")
fh.close()

file=open('exprsn .txt','r') #Display contents of file


s=' '
while s:
s=file.readline()
l=s.split()
hash_content='#'.join(l)
print(hash_content,end='')
file.close()

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q8) Write a program to create a file named whorules.txt, with the following lines of text. Read this
text file and display the total number of vowels/ consonants/ uppercase/ lowercase characters present
in the file.
”Be confident in yourself. Nobody can make you feel inferior without your permission. Always look
forward. You can never plan the future by looking the past.”
Code:
#Q8
fh=open('whorules.txt','w') #Write in file
fh.write('Be confident in yourself. Nobody can make you feel inferior without your permission. Always
look forward.\
You can never plan the future by looking the past.')
print("Contents written in file")
print('\n')

fh.close()

file=open('whorules.txt','r') #Read from file


v='AEIOUaeiou'

c='BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz'
s=' '
UC,LC,VC,CC=0,0,0,0
while s:

s=file.read(1)
if s.isupper():
UC+=1
elif s.islower():
LC+=1
if s in v:
VC+=1
elif s in c:

CC+=1
print(f'Total number of uppercase letters = {UC}')
print(f'Total number of lowercase letters = {LC}')
print(f'Total number of vowels = {VC}')
print(f'Total number of consonants = {CC}')
file.close()

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q9) Read the text file named expressn.txt that stores the following text. Count the total number of
occurrences of the word ‘it’ and ‘is’ separately
Nothing in life is to be feared,\n as it takes you nowhere.\n Worry is like a rocking chair\n: It gives
you something to do\n but never gets you anywhere.
Code:
#Q9
fh=open('expressn.txt','r')
s=' '

isc,itc=0,0
while s:
s=fh.readline()
s=s.split()

for i in range(len(s)):
if 'is'==s[i]:
isc+=1
if 'it'==s[i]:
itc+=1
fh.close()
print("Number of 'is' in text =",isc)
print("Number of 'it' in text =",itc)

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q10) Write a menu driven program
i. To create a binary file named records.dat, with some names and roll numbers taken from user &
stored in the file.
ii. To print all the records in a formatted manner.
iii. Search for a given roll number and display the name. If the given roll no is not found in the file
display an appropriate message.
iv. Exit
Code:

#Q10
import pickle
def write(): #Write in a binary file
d={}

file=open("recored.dat",'wb')
ans='y'
while ans=='Y' or ans=='y':
name=input("Enter name of student: ")
rno=int(input("Enter roll no. of student: "))
d[rno]=name
ans=input('Do you want to continue Y/N: ')
pickle.dump(d,file)

print("Record written in file")


file.close()

def print_rec(): #Print record of file


fh=open("recored.dat",'rb')
try:
while(1):
rec=pickle.load(fh)

print('Roll no','\t','Name')
for k in rec:
print(f'{k}\t{rec[k]}')
except EOFError:

pass
fh.close()

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
def search(): #Search roll number in file
fh=open("recored.dat",'rb')
r=int(input('Enter a roll number: '))

try:
while(1):
rec=pickle.load(fh)
print('Roll no','\t','Name')
for k in rec:
if k==r:
print(f'{k}\t{rec[k]}')
break

else:
print(r,'not in record')
except EOFError:
pass

fh.close()

while(1):
print('\t','Choose a Number','\t')

print('1','\t','To create a binary file named records.dat')


print('2','\t','To print all the records in a formatted manner.')
print('3','\t','Search for a given roll number and display the name.')
print('4','\t','Exit')

no=int(input("Choose a Number: "))


if no==1:
write()
elif no==2:

print_rec()
elif no==3:
search()
elif no==4:

print('You choose to exit')


break

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
else:
print('Invalid choice\nTry again')

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q11) Create a binary file named result.dat, to stores some roll number, name and marks of 4
students. Accept a roll number and new marks of the student from the user. Update this marks into
the file.
Code:

#Q11
import pickle
fh=open('result.dat','wb')
for i in range(4):

l=[]
rno=int(input("Enter roll number of student: "))
name=input("Enter name of student: ")
mks=int(input("Enter marks of student: "))

rec=[rno,name,mks]
l.extend(rec)
pickle.dump(l,fh)
print("Record written")
print()
fh.close()

file=open('result.dat','rb+')

r=int(input("Enter roll number: "))


nmks=int(input("Enter new marks: "))
found=False
try:
while(1):
pos=file.tell()
rec=pickle.load(file)
if rec[0]==r:

rec[2]=nmks
file.seek(pos)
pickle.dump(rec,file)
file.seek(pos)

print(pickle.load(file))
found=True

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
except EOFError:
if found==False:
print("No record found")

else:
print('Updated')
file.close()

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q12) Write a menu driven program
i. To create a CSV file named Employee.csv, with EmpName, EmpCode and Salary taken from user.
ii. To print all the records.

iii. Search for a record with a given Employee number and display the Details.
iv. Display record of the employee getting the highest salary.
v. Exit
Code:
#Q12
import csv
def write(): #Write csv file
fh=open('Employee.csv','w',newline='')

writer=csv.writer(fh)
n=int(input("Enter number of employee: "))
for i in range (n):
l=[]

Empname=input("Enter name of employee: ")


EmpCode=int(input("Enter employee code: "))
Salary=int(input("Enter salary of employee: "))
rec=[Empname,EmpCode,Salary]

l.extend(rec)
writer.writerow(l)
fh.close()
print('Record written in file')

def print_rec(): #print record of csv file


fh=open('Employee.csv','r')
reader=csv.reader(fh)
print('Name','\t','Code','\t','Salary')

for row in reader:


print(row[0],'\t',row[1],'\t',row[2])
fh.close()
def search(): #search employee

Empno=int(input("Enter Employee number to be searched: "))


fh=open('Employee.csv','r')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
reader=csv.reader(fh)
for row in reader:
if row[1]==str(Empno):

print('Name:','\t',row[0])
print('Code:','\t',row[1])
print('Salary:','\t',row[2])
break
else:
print('No record found')
fh.close()
def maxsal_emp(): #Employee with highest salary

fh=open('Employee.csv','r')
reader=csv.reader(fh)
mx=0
for row in reader:

if int(row[2])>mx:
mx=int(row[2])
nm=row[0]
cd=row[1]

print('Name:','\t',nm)
print('Code:','\t',cd)
print('Salary:','\t',mx)
fh.close()

while(1):
print('\t','Choose a Number','\t')
print('1','\t','To create a CSV file named Employee.csv')
print('2','\t','To print all the records')

print('3','\t','Search for a record with a given Employee number')


print('4','\t','Display record of the employee getting the highest salary.')
print('5','\t','Exit')
no=int(input("Choose a Number: "))

if no==1:
write()

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
elif no==2:
print_rec()
elif no==3:

search()
elif no==4:
maxsal_emp()
elif no==5:
print("You choose to exit")
break
else:
print("Invalid Choice\nTry again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q13) Write a program to store Roll Number, Name & Marks of few students into a file named
‘STUDENTS.CSV’. Read all the contents of ‘students.csv’ & display records of only those students
who has scored more than 80% marks.
Code:

#Q13
import csv
fh=open('student.csv','w',newline='') #Write in file
writer=csv.writer(fh)

n=int(input("Enter number of student: "))


for i in range (n):
l=[]
Name=input("Enter name of Student: ")

Rno=int(input("Enter Student Rno: "))


mks=int(input("Enter marks of employee: "))
rec=[Rno,Name,mks]
l.extend(rec)
writer.writerow(l)
fh.close()

file=open('student.csv','r') #Read from file

reader=csv.reader(file)
found=0
print('Rno','\t','Name','\t','Marks')
for row in reader:
if int(row[2])>80:
print(f'{row[0]}\t{row[1]}\t{row[2]}')
found=1
if found==0:

print('No Record found')


file.close()

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Q14) Write a menu driven program to perform the following operations on a Stack to store records
of book details (bookNo, bookName) using function:
a. Push operation
b. Pop operation
c. Peek operation

d. Display all elements from a stack


Code:
stack=[]
def push():

bno=int(input("Enter book number: "))


bnm=input("Enter book name: ")
stack.extend([bno,bnm])
print("New stack is",stack)

def pop():
if stack==[]:
print('Stack is empty')

else:
elt=stack.pop()
print('Element removed: ',elt)
print('Stack:',stack)

def peek():
if stack==[]:
print('Stack is empty')
else:
top=stack[len(stack)-1]
print("Topmost element=",top)

def display():
if stack==[]:
print('Stack is empty')
else:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print('Elements in stack are: ')
for i in range(len(stack)-1,-1,-1):
print(stack[i])

while(1):
print('\t','Choose a Number','\t')
print('1','\t','To push elements in the stack')
print('2','\t','To remove an element from the stack')
print('3','\t','To display its topmost element')
print('4','\t','To Dispaly all the elements')
print('5','\t','Exit')

no=int(input("Choose a Number: "))


if no==1:
push()
elif no==2:

pop()
elif no==3:
peek()
elif no==4:

display()
elif no==5:
print("You choose to exit")
break

else:
print("Invalid choice\t Try again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q15) Write a Python program to implement a stack using a list and perform the following
operations based on a user menu:
1. Add a student record (ID, name, marks) onto the stack.
2. Remove the top student record from the stack.
3. Display the current student records in the stack.

4. Exit
Code:

stack=[]
def push():
sid=int(input("Enter student ID "))
snm=input("Enter Student Name: ")
mks=int(input("Enter marks: "))
stack.extend([sid,snm,mks])
print("New stack is",stack)

def pop():
if stack==[]:
print('Stack is empty')
else:
elt=stack.pop()
print('Element removed: ',elt)
print('Stack:',stack)

def display():
if stack==[]:
print('Stack is empty')
else:
print('Elements in stack are: ')
for i in range(len(stack)-1,-1,-1):
print(stack[i])

while(1):
print('\t','Choose a Number','\t')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print('1','\t','Add a student record (ID, name, marks) onto the stack.')
print('2','\t','Remove the top student record from the stack')
print('3','\t','Display the current student records in the stack')
print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:
push()
elif no==2:
pop()
elif no==3:
display()
elif no==4:
print("You choose to exit")
break
else:
print("Invalid choice\nTry again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q16) BCCI has created a dictionary containing top players and their runs as key value pairs of
cricket team. Write a program, with separate user defined functions to perform the following
operations:
Push the name of the players (provided as keys) of the dictionary into a stack, where the
corresponding runs (value) is greater than 49. Pop and display the content of the stack.
Code:
stack={}
def push():
ans='y'
while ans=='y' or ans=='Y':
nm=input("Enter the name of the cricketer")

scr=int(input("Enter runs made by the cricketer"))


if scr>49:
stack[nm]=scr
ans=input("Do you want to continue y/n")

print('Stack created = ',stack)

def pop():
if stack=={}:

print('Stack is empty')
else:
lst=list(stack.keys())
elt=stack.pop(lst[-1])

print('Stack:',stack)

def display():
if stack=={}:

print("Stack is empty")
else:
print('Elements in stack are: ')
lst=list(stack.keys())

for i in range (len(lst)-1,-1,-1):


print(lst[i])

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
while(1):
print('\t','Choose a Number','\t')
print('1','\t','Push name of players and corresponding runs as key:value pairs in the stack.')

print('2','\t','Remove the topmost data in the stack')


print('3','\t','Display the contents of the stack')
print('4','\t','Exit')
no=int(input("Choose a Number: "))
if no==1:
push()
elif no==2:
pop()

elif no==3:
display()
elif no==4:
print("You choose to exit")

break
else:
print("Invalid choice\nTry again")

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q17) Write a Python code to connect a MySQL database namely SHOP and use the following table
Stationary and Consumer and send SQL commands to the database and retrieve the records based
on the queries given below:

(i) To display the details of those consumers whose Address is Delhi.


(ii) To display the details of Stationary whose Price is in the range of 8 to 15. (Both Value
included)
(iii) To display the ConsumerName, Address from Table Consumer, and Company and Price
from table Stationary, with their corresponding matching S_ID.
(iv) Display the maximum and minimum price for each company.
Code:
import mysql.connector as sq

connect=sq.connect(host='localhost',user='root',database='shop',passwd='NimaLi0611')
if connect.is_connected():
print('Connected')
else:

print('Error while connection')


cur=connect.cursor()
while(1):
print('Choose a number')

print('1','\t','To display the details of those consumers whose Address is Delhi.')


print('2','\t','To display the details of Stationery whose Price is in the range of 8 to 15.')
print('3','\t','To display the ConsumerName, Address from Table Consumer, and Company and Price
from\
table Stationery, with their corresponding matching S_ID.')
print('4','\t','Display the maximum and minimum price for each company.')
print('5','\t','Exit')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
no=int(input("Choose a Number: "))
if no==1:
cur.execute('select * from consumer where Address="Delhi"')

data=cur.fetchall()
for row in data:
print(row[0],'\t',row[1],'\t',row[2],'\t',row[3])
elif no==2:
cur.execute('select * from stationary where Price between 8 and 15')
data=cur.fetchall()
for row in data:
print(f'{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}')

elif no==3:
rec='select ConsumerName,Address,Company,Price,C.S_ID from Consumer C,Stationary S where
S.S_ID=C.S_ID'
cur.execute(rec)
data=cur.fetchall()
for row in data:

print(f'{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}\t{row[4]}')
elif no==4:
rec='select Company,max(Price),min(Price) from stationary group by Company'
cur.execute(rec)

data=cur.fetchall()
for row in data:
print(f'{row[0]}\t{row[1]}\t{row[2]}')
elif no==5:
print('You choose to exit')
break
Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q18) Using Python MySQL Connector, create a student table and insert the following data.

ID Name Class Mark Sex


1 John Doe Four 75 female
2 Max Ruin Three 85 male
3 Arnold Sun Three 55 male
4 Krish Star Four 60 female
Using Python MySQL Connector, execute the following SQL commands on the above student table
& display appropriate message.
i. Add a new attributes - Sec char(3) to the table
ii. UPDATE table to add Sec as A for all class 3 students
iii. ORDER By to display data in descending order
iv. GROUP BY and find the min, max, sum, count and average mark
v. DELETE to remove tuple(s) belonging to class 4

Code:
import mysql.connector as sq
connect=sq.connect(host='localhost',user='root',database='student',passwd='NimaLi0611')
if connect.is_connected():

print('Connected')
else:
print('Error while connection')
cur=connect.cursor()

while(1):
print('\tChoose a Number\t')
print(f'1\tAdd a new attributes - Sec char(3) to the table')
print(f'2\tUPDATE table to add Sec as A for all class 3 students')
print(f'3\tORDER By to display data in descending order')
print(f'4\tGROUP BY and find the min, max, sum, count and average mark')
print(f'5\tDELETE to remove tuple(s) belonging to class 4')
print(f'6\texit')

n=int(input("Choose a Number: "))


if n==1:
cur.execute('Alter table student add Sec char(1)')
connect.commit()

print('Added\n')
if n==2:
cur.execute('Update student set Sec="A" where Class="Three"')
connect.commit()

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print('Updated\n')
if n==3:
cur.execute('Select * from student order by ID desc')

data=cur.fetchall()
print('ID','\t','Stu Name','\t','Class','\t','Mark','\t','Sex','\t','Sec')
for row in data:
print(row[0],'\t',row[1],'\t',row[2],'\t',row[3],'\t',row[4],'\t',row[5])
print('\n')
if n==4:
cur.execute('Select Class,min(Mark),max(Mark),sum(Mark),Count(Mark),avg(Mark) from student
group by Class')
data=cur.fetchall()
print('Class','\t','Min','\t','Max','\t','Sum','\t','Count','\t','Average')

for row in data:


print(row[0],'\t',row[1],'\t',row[2],'\t',row[3],'\t',row[4],'\t',row[5])
print('\n')
if n==5:

cur.execute('Delete from student where class="Four"')


connect.commit()
print('Deleted\n')
if n==6:

print('You choose to exit')


break

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q19) Write a Python code to connect a MySQL database namely SUPERMART and use the
following table Items and Consumer and send SQL commands to the database and retrieve the
records based on the queries given below:

(i) To display the details of those customers who purchased Milk.


(ii) To display the details of Items supplied by Amul.

(iii) To display the Name of the different cities listed in Table Customers
(iv) Display details of all customers with their name stating with ‘M’
Code:
import mysql.connector as sq

connect=sq.connect(host='localhost',user='root',database='SUPERMARKET',passwd='NimaLi0611')
if connect.is_connected():
print('Connected')
else:
print('Error while connection')
cur=connect.cursor()
while(1):
print('\tChoose a Number\t')

print(f'1\tTo display the details of those customers who purchased Milk.')


print(f'2\tTo display the details of Items supplied by Amul.')
print(f'3\tTo display the Name of the different cities listed in Table Customers')
print(f'4\tDisplay details of all customers with their name stating with ‘M’')

print(f'5\texit')
n=int(input("Choose a Number: "))
if n==1:
cur.execute('Select * from Items where ItemName="Milk"')

data=cur.fetchall()
print('I_ID','\t','I_Name','\t','Supplier','\t','Rate')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
for row in data:
print(row[0],'\t',row[1],'\t',row[2],'\t',row[3])
print('\n')

elif n==2:
cur.execute('Select * from Items where Supplier="AMUL"')
data=cur.fetchall()
print('I_ID','\t','I_Name','\t','Supplier','\t','Rate')
for row in data:
print(row[0],'\t',row[1],'\t',row[2],'\t',row[3])
print('\n')
elif n==3:

cur.execute('Select distinct Address from Customers')


data=cur.fetchall()
print('Address')
for row in data:

print(row[0])
print('\n')
elif n==4:
cur.execute('Select * from customers where CustomerName like "M%"')

data=cur.fetchall()
print('C_ID','\t','CustomerName','\t','Address','\t','I_ID')
for row in data:
print(row[0],'\t',row[1],'\t',row[2],'\t',row[3])

print('\n')
elif n==5:
print('You choose to exit')
break

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Q20) Using Python MySQL Connector, create a patient table and insert the following data.

Using Python MySQL Connector, execute the following SQL commands on the above patient table
i. Insert a new patient record with details accepted from the user
ii. Change ‘Hypo Thyroid’ to ‘Hyper Thyroid’ for Dharam Pal
iii. Display all records with descending ORDER of their Bill amount

iv. DELETE records for the patients having tonsil.


Code:
import mysql.connector as sq
connect=sq.connect(host='localhost',user='root',database='Patients',passwd='NimaLi0611')

if connect.is_connected():
print('Connected')
else:
print('Error while connection')

cur=connect.cursor()
cur.execute('create table if not exists Patients(P_ID char(3) not null primary key, P_Name char(30)\
not null, P_History char(20) not null, Bill_Amt int)')
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format('P01','Dilip Singh','Diabetes',52000))
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format('L02','Vidya Ahuja','High BP',47000))
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format('T05','Dharam Pal','Hypo Thyroid',7500))
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format('F03','Ved Prakash','Diabetes',25000))
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format('M04','Adiba Patel','Tonsils',9000))
connect.commit()
while(1):
print('\tChoose a Number\t')

print(f'1\tInsert a new patient record with details accepted from the user')
print(f'2\tChange ‘Hypo Thyroid’ to ‘Hyper Thyroid’ for Dharam Pal')

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
print(f'3\tDisplay all records with descending ORDER of their Bill amount')
print(f'4\tDELETE records for the patients having tonsil.')
print(f'5\texit')

n=int(input("Choose a Number: "))


if n==1:
PID=input('Enter Patient ID: ')
Pnm=input('Enter Patients Name: ')
PHstry=input("Enter Patients History: ")
bill=int(input("Enter Patients Bill Amount: "))
cur.execute('insert into patients(P_ID,P_Name,P_History,Bill_Amt) values ("{}","{}","{}",{})'\
.format(PID,Pnm,PHstry,bill))
connect.commit()
print('Inserted\n')

elif n==2:
cur.execute('Update patients set P_History="Hyper Thyroid" where P_Name="Dharam Pal"')
connect.commit()
print('Updated\n')

elif n==3:
cur.execute('Select * from patients order by Bill_Amt desc')
data=cur.fetchall()
for row in data:

print(row[0],'\t',row[1],'\t',row[2],'\t',row[3])
print('\n')
elif n==4:
cur.execute('Delete from patients where P_History="Tonsils"')
connect.commit()
print('Deleted\n')
elif n==5:
print('You Choose to exit')

break

Output:

Name-Nidhi Salian Academic year- Computer Science


Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal
Name-Nidhi Salian Academic year- Computer Science
Class-XII-S2 2023-2024 Journal

You might also like