0% found this document useful (0 votes)
118 views33 pages

COMP Class-XII Practical File 2024-25

Uploaded by

tgtoyt6
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)
118 views33 pages

COMP Class-XII Practical File 2024-25

Uploaded by

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

CLASS – XII COMPUTER SCIENCE (Code No.

083) PRACTICAL PROGRAMS LIST FOR RECORD 2024-2025

CLASS – XII COMPUTER SCIENCE (Code No. 083)


SYLLABUS : 2024-2025

1. Prerequisites Computer Science- Class XI 5. Practical

2. Learning Outcomes Student should be able to


S.No Unit Name Marks (Total=30)
a) apply the concept of function. Lab Test:
1. Python program (60% logic + 20% documentation + 8
b) explain and use the concept of file handling. 20% code quality)
1
c) use basic data structure: Stacks
2. SQL queries (4 queries based on one or two tables) 4
d) explain basics of computer networks.
Report file:
• Minimum 15 Python programs.

DON'T WRITE
e) use Database concepts, SQL along with connectivity between Python and SQL.
3. Distribution of Marks: • SQL Queries – Minimum 5 sets using one table /
2 7
two tables.
Unit Periods • Minimum 4 programs based on Python – SQL
Unit Name Marks
No. Theory Practical connectivity
1

2
Computational Thinking and
Programming-2
Computer Networks
THIS PAGE
40

10
70

15
50


3

4
Project:
(using concepts learnt in Classes 11 and 12)

Viva voce
8

3
3 Database Management 20 25 20

Total 70 110 70

4. Suggested Reading Material

● NCERT Textbook for COMPUTER SCIENCE (Class XII)

● Support Materials on the CBSE website.


WHITE PAGE ROLLING PAGE

Q1. Sample Run and Output: 1. Write a program to calculate simple interest using a function interest () that can
receive principal amount, time and rate and returns calculated simple interest .
Enter principal amount : 6700
Do specify default values for rate and time as 10% and 2 years respectively.
Simple interest with default ROI and time values = Rs. 1340.0
Program Code:
Enter rate of interest (ROI) : 8

Enter time in years : 3 def interest(principal, time=2, rate=0.10) :

Simple interest with your provided ROI and time values = Rs. 1608.0 return principal*rate*time

# __main program__

principal=float(input( "Enter principal amount :" ))


SI_1 = interest(principal)
print( "Simple interest with default ROI and time values = Rs." , SI_1)
ROI= float(input( "Enter rate of interest (ROI):" ))
Time=int(input("Enter time in years : "))
SI_2 = interest(principal, Time, ROI/100)
print( "Simple interest with your provided ROI and time values = Rs." , SI_2)
WHITE PAGE ROLLING PAGE
Q2. Sample Run and Output: 2. Write a python program to accept a word in lowercase and pass it to a function.
Arrange all the letters of the word in its alphabetical order and display the result.
Enter a word in lowercase : computer
Sample Input : computer
Dictionary Order : cemoprtu Sample Output : cemoprtu

Program Code:

# To arrange the letters in dictionary order


def Arrange(wd) :
p = len(wd)
word = ‘ ‘
for i in range(65 , 91):
for k in range(0 , p):
ch = wd[k]
if (ch==chr(i) or ch==chr(i+32)):
word = word+ch
return word

# __main program__
wd = input(“ Enter a word in lowercase : ”)
wd = wd.lower()
wd1 = Arrange(wd)
print( “ Dictionary Order : “ , wd1)
WHITE PAGE ROLLING PAGE
Q3. Sample Run and Output: 3. Write a program that should prompt the user to type some sentence(s)
followed by "enter". It should then print the original sentence(s) and the
Enter a few sentences: Python was conceived in the late 1980s by Guido van following statistics relating to the sentence(s):
Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its • Number of words
implementation began in December 1989. Python 3.0 was released on 3 December • Number of characters (including white-space and punctuation)
2008.
• Percentage of characters that are alpha numeric
Hints: Assume any consecutive sequence of non-blank characters in a word.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde Program Code:
& Informatica (CWI) in the Netherlands. Its implementation began in December
def Count_W_C_AN(str):
1989. Python 3.0 was released on 3 December 2008.
length = len(str)
Number of words = 34 spaceCount = 0
Number of characters = 205
Alphanumeric Percentage = 80.48780487804879 alnumCount = 0
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = alnumCount / length * 100
print(" \n Original Sentences: ")
print(str, ”\n”)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)
# __ Main Program__
Sentences = input("Enter a few sentences: ")
Count_W_C_AN(Sentences)
WHITE PAGE ROLLING PAGE
Q4. Sample Run and Output: 4. Write a python menu based program using user defined function
1. Addition ArithmeticOP( ) to find addition, subtraction, multiplication, division of two
2. Subtraction values given by user.
3. Multiplication
4. Division
Enter your choice of operation out of (1, 2, 3, 4) :1 Program Code:
Enter the first number :5 “”” Menu based program to find addition, subtraction, multiplication,
Enter the second number :2
Addition of 5 and 2 = 7 division of two values.”””
Do you want to do another operation? Press(y/n)y
1. Addition def ArithmeticOP( Ch, N1,N2 ):
2. Subtraction if Ch==1:
3. Multiplication
4. Division
print( " Addition of " , N1," and " , N2, " = ", N1+N2)
Enter your choice of operation out of (1, 2, 3, 4) :2 elif Ch==2:
Enter the first number :10 print( " Subtraction of " , N1," and " , N2, " = ", N1-N2)
Enter the second number :2
Subtraction of 10 and 2 = 8 elif Ch==3:
Do you want to do another operation? Press(y/n)y print( " Multiplication of " , N1," and " , N2, " = ", N1*N2)
1. Addition
elif Ch==4:
2. Subtraction
3. Multiplication print( " Division of " , N1," and " , N2, " = ", N1/N2)
4. Division else:
Enter your choice of operation out of (1, 2, 3, 4) :3
Enter the first number :8
print("Wrong choice")
Enter the second number :2
Multiplication of 8 and 2 = 16 # __Main Program__
Do you want to do another operation? Press(y/n)y
1. Addition
2. Subtraction
Ans="y"
3. Multiplication
4. Division while Ans.lower()=="y":
Enter your choice of operation out of (1, 2, 3, 4) :4 print (" 1. Addition ")
Enter the first number :16
Enter the second number :8
print (" 2. Subtraction ")
Division of 16 and 8 = 2.0 print (" 3. Multiplication ")
Do you want to do another operation? Press(y/n)y print (" 4. Division ")
1. Addition
2. Subtraction C=int(input(" Enter your choice of operation out of (1, 2, 3, 4) : "))
3. Multiplication N1=int(input(" Enter the first number :"))
4. Division
N2=int(input(" Enter the second number :"))
Enter your choice of operation out of (1, 2, 3, 4) :5
Enter the first number :4 ArithmeticOP(C, N1, N2)
Enter the second number :2 Ans=input( "Do you want to do another operation? Press(y/n)" )
Wrong choice
Do you want to do another operation? Press(y/n)n
else:
Thank you. print( "Thank you." )
ROLLING PAGE
WHITE PAGE
5. Write a Python code to accept an integer number. Pass it to a function
Q5. Sample Run and Output: which returns its number of factors. Finally, display whether the number is a
Enter a number : 7 prime number or not.
Factors of 7 are given below :
Program Code:
1, 7,
Total number of factors are = 2 def Prime(n1):
7 is a prime number. c=0
n=n1
=====RESTART: Practical-Q5.py =======
print( " Factors of ", n , "are given below : ")
Enter a number : 12 for a in range(1, n+1):
Factors of 12 are given below : if(n%a==0):
print( a , end=", ")
1, 2, 3, 4, 6, 12,
c=c+1
Total number of factors are = 6 return c
12 is not a prime number.
# Main Program

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


P = Prime(N)
print(" \n Total number of factors are = ", P)

if(P==2):
print( N , " is a prime number.")
else:
print( N , " is not a prime number.")
WHITE PAGE ROLLING PAGE
Q6. Sample Run and Output: 6. Write a Python code to accept two numbers from the user and find the
H.C.F. and L.C.M. Use a function to return H.C.F. of the numbers.
Enter the first number: 25 Calculate the L.C.M. in the main program .
Hint: L.C.M. = (Product of the numbers) / H.C.F.
Enter the Second number: 45 Program Code:

The HCF of two numbers = 5 # To and find the H.C.F. and L.C.M. by using function.
def HCF(n1,n2):
The LCM of two numbers = 225 a, b = n1, n2
p= a * b
for i in range ( 1, p):
if ((a% i == 0) and (b % i == 0)):
gcd = i
return gcd

# __Main Program__

N1= int( input(" Enter the first number: "))


N2= int( input(" Enter the Second number: "))

HCF = HCF(N1, N2)


LCM = int((N1 * N2)/ HCF)

print( " The HCF of two numbers = " , HCF)


print( " The LCM of two numbers = " , LCM)
WHITE PAGE ROLLING PAGE
Q7. Sample Run and Output: 7. Write a function that takes a number n and then returns three randomly
generated numbers having exactly n digits (not starting with zero) e.g., if n
Enter the value of n : 3 is 2 then function can randomly return a number 10-99 but 07, 02 etc. are
not valid two-digit numbers.

Random number- 1 = 527 Solution

Random number- 2 = 805 import random


def generate_number(n):
Random number- 3 = 680 lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)

# __Main Program__

n = int(input("Enter the value of n:"))

for i in range(3):
random_number = generate_number(n)
print("Random number-",i+1, "=", random_number)
WHITE PAGE ROLLING PAGE
Q8. Sample Run and Output: 8. Write a function LShift(Arr, n) in Python , which accepts a list Arr of numbers and
n is a numeric value by which all elements of the list are shifted to left. Also
Enter numbers in a list form :[10,20,30,40,12,11]
show the maximum, minimum and summation of the numbers of the list.
Enter value by which all elements of the list are shifted :2 Sample input data of the list : Arr= [10, 20, 30, 40, 12, 11] and n=2
The List after shifting the elements [30, 40, 12, 11, 10, 20] Output: Arr = [30, 40, 12, 11, 10, 20]

Maximum number in the List = 40


Program Code:
Minimum number in the List = 10
def LShift(Arr, n):
Summation of all the numbers in the List = 123 L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0, L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y

print("The List after shifting the elements", Arr)


return Arr

# __ Main Program__

Data=eval(input(" Enter numbers in a list form :"))


N=int(input(" Enter value by which all elements of the list to be shifted:"))

NArr=LShift(Data, N)

print( " Maximum number in the List = " , max(NArr))


print( " minimum number in the List = " , min(NArr))
print( " Summation of all the numbers in the List = " , sum(NArr))
WHITE PAGE ROLLING PAGE
9. Write a function that receives an octal number and prints the equivalent
Q9. Sample Run and Output: number in other number bases i.e. in binary, decimal, and hexadecimal
equivalents.
Enter an octal number : 15
entered/passes Octal number : 15 Program Code:
Binary number : 0b1101 # Octal number to other number system (Type Conversion)
Decimal number : 13
Hexadecimal number : 0xd def Oct_2_Other(N):
print( " entered/passes Octal number : ", N)
NStr=str(N)
DN=int(NStr , 8)
print( " Binary number : ", bin(DN))
print( " Decimal number : ", DN)
print( " Hexadecimal number : ", hex(DN))

# __ Main Program __

octNum=int(input(" Enter an octal number : "))

Oct_2_Other(octNum)
WHITE PAGE ROLLING PAGE
Q10. Sample Run and Output: 10. Write function show() in python to open a file “INDIA.TXT”. Read the lines of
the file to find and display the occurrence of the word “India”. Also, display
total number of lines and characters in the file. The text file contents are:
Total no of word 'India' in the file= 4
_____________________ INDIA.TXT______________________
Total no of lines in the file= 4 India is the fastest growing economy.
India is looking for more investments around the globe.
Total no of Characters in the file= 227 The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.
____________________________________________________
Program Code:

def display():
cw=0
L=0
ch=0
file=open("INDIA.txt", 'r')

for Line in file:


L=L+1
ch=ch+len(Line)
words=Line.split()
for w in words:
if w=="India":
cw=cw+1

print(" Total no of word 'India' in the file=", cw)


print( " Total no of lines in the file=", L)
print( " Total no of Characters in the file=", ch)

# __ Main program __

display()
WHITE PAGE ROLLING PAGE
Q11. Sample Run and Output: 11. Write function Tabulation() to open a file “Result.txt” in ‘w+’ mode to store
Enter records in the file: index number, name and marks of few students. The number of records to be
****************************** entered into the file will be based on the user’s choice. Use the same file
Enter student's Index number : 01 (without reopening ) to retrieve its records and display them on the screen.
Enter student's name : Rahul Kumar Program Code:
Enter student's mark : 517 # To enter records in the text file using ‘w+’ mode.
Do you want to add more records? press(Y/N): y def Tabulation( ):
Enter student's Index number : 02 f = open("Result.txt", 'w+')
Enter student's name : Geeta Dutta ch='y'
Enter student's mark : 498 print("Enter records in the file:")
Do you want to add more records? press(Y/N): y print("*"*30)
Enter student's Index number : 03
Enter student's name : Deepak Sharma while ch.lower()=='y':
Enter student's mark : 525 Ino=input(" Enter student's Index number : ")
Do you want to add more records? press(Y/N): n name=input(" Enter student's name : ")
File saved. marks=input(" Enter student's mark : ")
Content of the file : rec = Ino+" "+name+" "+marks+'\n'
****************************** ch=input(" Do you want to add more records? press(Y/N): ")
01 Rahul Kumar 517 f.write(rec)
02 Geeta Dutta 498 print(" File saved. " )
03 Deepak Sharma 525
****************************** # To display records of the text file
print(" Content of the file : ")
print("*"*30)
f.seek(0) # sets the file pointer at the beginning.
rec=True
while rec:
rec=f.readline()
print(rec, end='')
f.close()
print("*"*30)
# __Main Program __
Tabulation( )
WHITE PAGE ROLLING PAGE
Q12. Sample Run and Output: 12. Write a function Add_Display () in python to open the file in an appropriate
mode to add and retrieve data. Add more two consumer’s name and phone
How many consumer's name & phone you will enter? : 2 number in the file. Without closing the file, retrieve data, count and display the
Enter consumer's name : Sumit names start with the letter ‘D’. Assume the file already exists in the system.
Enter consumer's phone : 7654390218
Program Code:
Enter consumer's name : Damini
# To add more data in the text file.
Enter consumer's phone : 6543217890
def Add_Display( ):
File saved.
n=int(input("How many consumers’ name & phone you will enter? : "))
Contents of the file :
f = open("Phone.txt", 'a+')
******************************
Dinesh--6789065432 for i in range(n):
Deepika--8765432109 Name=input("Enter consumer's name : ")
Dipankar--4567890392 Ph=input("Enter consumer's phone : ")
Daxit--7865493218 rec=Name + ' -- ' + Ph + '\n'
Damini--6543217890 f.write(rec)
Total number of consumers name start with 'D': 5 print(" File saved. " )
# To display names of the consumer start with letter 'D' from the file
Dinesh--6789065432 print(" Contents of the file : ")
Sital--345678901 print("*" * 30)
Alok--1234567890 f.seek(0) # sets the file pointer at the beginning.
Deepika--8765432109 line=f.readlines()
Binod--9087654321 C=0
Sovan--5678905432 for a in line:
Dipankar--4567890392 if a[0]=='D':
Rohan--2345678901 print(a, end=' ')
Chirag--9678567430 C=C+1
Hitesh--4567890312 print(" Total number of consumers name start with 'D': ", C )
Ganesh--9876543216 f.close()
Daxit--7865493218 print("*" * 30)

# __Main Program __

Add_Display( )
WHITE PAGE ROLLING PAGE
Q13. Sample Run and Output: 13. Write a python program that writes the given content in a text file “old.txt”.
Remove all the lines that contain the character 'a' in the file and write it to
OLD FILE CONTENTS
another text file “new.txt”. Display both the file contents.
==============================
“old.txt” file content:
Harry Potter
Harry Potter
There is a difference in all harry potter books.
There is a difference in all harry potter books.
We can see it as harry grows.
We can see it as harry grows.
The books were written by J.K rowling.
The books were written by J.K rowling.
Program Code:
******************************
“””remove all the lines that contain the character 'a' in a file and write it to another
file. Display both the file contents. “””
NEW FILE CONTENTS AFTER COPY (Lines without letter 'a')
============================== fo=open("old.txt","w")
The books were written by J.K rowling. fo.write(" Harry Potter \n")
fo.write("There is a difference in all harry potter books.\nWe can see it as harry
grows.\nThe books were written by J.K rowling. ")
fo.close()
fo=open('old.txt','r')
fn=open('new.txt','w+')
l=fo.readlines()
for i in l:
if 'a' not in i:
fn.write(i)

print( " OLD FILE CONTENTS ")


print("=" *30)
fo.seek(0) # sets the file pointer at the beginning.
print(fo.read())
print('\n', "*" *30 , '\n')

print( " NEW FILE CONTENTS AFTER COPY (Lines without letter 'a') \n ")
print("=" *30)
fn.seek(0)
print(fn.read())

fo.close()
fn.close()
WHITE PAGE ROLLING PAGE
Q14. Sample Run and Output: 14. Write a python function that reads a text file “BODYPARTS.txt” which is stored
in D drive of the system and display the number of vowels/ consonants/
OUTPUT :
uppercase/ lowercase/digit characters in the file.
The human body has 2 arms and 2 legs, 1 head and 1 neck, which connect to the Contents of “BODYPARTS.txt” :
torso. The body's shape is determined by a strong skeleton made of bone and The human body has 2 arms and 2 legs, 1 head and 1 neck, which connect to
cartilage, surrounded by fats(adipose tissue), muscle, connective tissue, organs, and the torso. The body's shape is determined by a strong skeleton made of bone
other structures. and cartilage, surrounded by adipose tissue, muscle, connective tissue,
organs, and other structures.
Vowels are : 72
Program Code:
consonants are : 126 “””Read a text file and display the number of vowels, consonants, uppercase,
Lower case letters are : 196 lowercase & digit characters in the file. ”””
def COUNT_VCULD():
Upper case letters are : 2 f=open("D:\\BODYPARTS.txt ","r")
cont=f.read()
Digits are : 4 print(cont)
vol = cons = LCC = UCC = digit = 0
for ch in cont:
if ch.isalpha():
if ch.lower() in ['a','e','i','o','u']:
vol+=1
else:
cons+=1
if ch.islower():
LCC+=1
else:
UCC+=1
elif ch.isdigit():
digit=digit+1
f.close()
print("Vowels are : ", vol)
print("consonants are : ", cons)
print("Lower case letters are : ", LCC)
print("Upper case letters are : ", UCC)
print("Digits are : ", digit)
# main program
COUNT_VCULD()
WHITE PAGE ROLLING PAGE
Q15. Sample Run and Output: 15. Consider the following definition of a train detail and write a method in Python
to write the content in a pickled file "TRAIN.DAT" and also display the contents
{'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
without closing the file after data entry. Assuming the binary file is containing
{'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'} the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
{'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'} Let the dictionary contained in file "TRAIN.DAT" be as shown below:
{'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'} Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
{'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'} Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
Program Code:
import pickle
Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
def Train_details():
with open("TRAIN.DAT ", 'wb+') as file:
pickle.dump(Train1, file)
pickle.dump(Train2, file)
pickle.dump(Train3, file)
pickle.dump(Train4, file)
pickle.dump(Train5, file)
file.seek(0) # sets the file pointer at the beginning.
try:
while True:
train_data = pickle.load(file)
print(train_data)
except EOFError:
file.close()
# __ main program __
Train_details ()
WHITE PAGE ROLLING PAGE
Q16. Sample Run and Output: 16. Write a function to search and display details of all trains, whose destination is
specified by user (e.g. "Delhi") from a binary file "TRAIN.DAT". Assuming the
Output
binary file is containing the objects of the following dictionary type:
Enter the destination place name: delhi
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
Train no: 1234
Answer
From: Mumbai
Let the dictionary contained in file "TRAIN.DAT" be as shown below:
To: Delhi
Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train no: 5678
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
From: Chennai
Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
To: Delhi
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train no: 7890
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
From: Pune
To: Delhi Program Code:
Search Successful import pickle
def search_trains(Destination):
found = False
try:
file = open("TRAIN.DAT", "rb")
while True:
trains = pickle.load(file)
if trains['To'] == Destination.capitalize():
print("Train no: ", trains['Tno'])
print("From: ", trains['From'])
print("To: ", trains['To'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
# __Main program__
Target_Place=input("Enter the destination place name:")
search_trains(Target_Place)
WHITE PAGE ROLLING PAGE
Q 17. Sample Run and Output: 17. A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
Output (ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter
Enter Book Number: 1008 and count and return number of books by the given Author are stored in the binary file
"Book.dat"
Enter Book Name: Three Thousand Stiches Let the file "Book.dat" include following data:
Enter Author Name: Sudha Murty Book1 = [1001, Midnight's Children, Salman Rushdie, 29.99]
Enter Price: 200 Book2 = [1004, A Suitable Boy, Vikram Seth, 59.9]
Book3 = [1003, The White Tiger, Aravind Adiga, 49.5]
Enter Author name to count books: Salman Rushdie Book4 = [1002, The Satanic Verses, Salman Rushdie, 39.23]
Search successful Program Code:
Number of books by Salman Rushdie : 2 import pickle
def CreateFile():
file = open("Book.dat", "ab")
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
def CountRec(authorName):
count = 0
found = False
try:
file = open("Book.dat", "rb")
while True:
record = pickle.load(file)
if record[2] == authorName:
count += 1
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search successful")
file.close()
return count
CreateFile()
author = input("Enter Author name to count books: ")
print("Number of books by", author, ":", CountRec(author))
WHITE PAGE ROLLING PAGE
Q18. Sample Run and Output: 18. Write a Python program to write a nested Python list to a csv file in one go.
After writing the CSV file read the CSV file and display the content those age is
Output
>=18. The CSV file content format and sample records are as follows:
How many records data you want to enter ? 3
['Name', 'Age', 'Gender']
Enter name : Prateek
['Prateek', '14', 'Male']
Enter Age : 14
['Ananya', '24', 'Female']
Enter gender : Male
['Aryan', '44', 'Male']
Enter name : Ananya
Program code:
Enter Age : 24
import csv
Enter gender : Female
def write_nested_list(data, file_name):
Enter name : Aryan
with open(file_name, 'w', newline='') as file:
Enter Age : 44
writer = csv.writer(file)
Enter gender : Male
writer.writerows(data)
========================================
Content of 'output.csv': def read_csv(file_name):
['Name', 'Age', 'Gender'] with open(file_name, 'r') as file:
['Ananya', '24', 'Female'] reader = csv.reader(file)
['Aryan', '44', 'Male'] print(next(reader))
for row in reader:
if int(row[1])>=18:
print(row)
# __main program __
nested_list=[ ]
Header=['Name', 'Age', 'Gender']
nested_list . append(Header)
N=int(input("How many records data you want to enter ? "))
for k in range(N):
Name=input(" Enter name : ")
Age=input("Enter Age : ")
Gender=input(" Enter gender : ")
Data=[Name, Age, Gender]
nested_list . append(Data)
write_nested_list(nested_list, 'output.csv')
print("=" * 40 , "\n Content of 'output.csv' having age >=18 :")
read_csv('output.csv')
WHITE PAGE ROLLING PAGE
Q 19. Sample Run and Output: 19. Write a Program in Python that defines and calls the following user defined functions :
(a) add(). To accept and add data of an employee to a CSV file 'furdata.csv'. Each record
Output consists of a list with field elements as fid, fname and fprice to store furniture id, furniture
Enter furniture id: 9 name and furniture price respectively.
Enter furniture name: desk (b) search(). To display the records of the furniture whose price is more than 10000.
Enter furniture price: 3000 Let the file "furdata.csv" include following data:
Record added successfully to 'furdata.csv' [1, table, 20000]
Records of furniture with price more than 10000: [2, chair, 12000]
Furniture ID: 1 [3, board, 10000]
Program Code:
Furniture Name: table
import csv
Furniture Price: 20000 def add():
with open('furdata.csv', 'a', newline='') as file:
Furniture ID: 2 writer = csv.writer(file)
Furniture Name: chair fid = input("Enter furniture id: ")
Furniture Price: 12000 fname = input("Enter furniture name: ")
fprice = float(input("Enter furniture price: "))
writer.writerow([fid, fname, fprice])
print("Record added successfully to 'furdata.csv'")

def search():
found = False
with open('furdata.csv', mode='r') as file:
reader = csv.reader(file)
print("Records of furniture with price more than 10000:")
for row in reader:
if len(row) == 3 and float(row[2]) > 10000:
print("Furniture ID:", row[0])
print("Furniture Name:", row[1])
print("Furniture Price:", row[2])
print()
found = True

if found == False:
print("No records of furniture with price more than 10000 found")

add()
search()
WHITE PAGE ROLLING PAGE
Q20. Sample Run and Output: 20. Julie has created a dictionary containing names and marks as key value pairs of 6
students. Write a program, with separate user defined functions to perform the
TOM ANU BOB OM following operations
Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 75.
Pop and display the content of the stack.
For example If the sample content of the dictionary is as follows
R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”:65, ‘’ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM
Program code:

R={"OM":76,"JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}

def PUSH(S, N):


S.append(N)

def POP(S):
if S!=[]:
return S.pop( )
else:
return None
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST, k)
while True:
if ST!=[ ]:
print(POP(ST),end=" ")
else:
break
WHITE PAGE ROLLING PAGE
Q21. . Sample Run and Output: 21. Write a program to implement the stack operations (add/push, delete/pop,
================================================== display) for the employee details (empno, name).
1. Push Program code:
2. Pop stk=[]
3. Display top=-1
4. Exit def line():
print('='*50) # To display a double line design as separator
Enter your choice:1
def isEmpty():
Enter the employee number to push:1 global stk
Enter the employee name to push:Bikash Dash if stk==[]:
Element Pushed print("Stack is empty!!!")
================================================== else:
None
1. Push
def push():
2. Pop global stk
3. Display global top
4. Exit empno=int(input("Enter the employee number to push:"))
Enter your choice:1 ename=input("Enter the employee name to push:")
stk.append([empno,ename])
Enter the employee number to push:2 top=len(stk)-1
Enter the employee name to push:Alok Sharma def display():
Element Pushed global stk
================================================== global top
if top==-1:
1. Push
isEmpty()
2. Pop else:
3. Display top=len(stk)-1
4. Exit print(stk[top],"<--top")
for i in range(top-1,-1,-1):
Enter your choice:3
print(stk[i])
[2, 'Alok Sharma'] <--top def pop_ele():
[1, 'Bikash Dash'] global stk
================================================== global top
1. Push if top==-1:
isEmpty()
2. Pop else:
3. Display stk.pop()
4. Exit top=top-1
Enter your choice:2 def main():
================================================== while True:
line()
1. Push print("1. Push")
2. Pop print("2. Pop")
3. Display print("3. Display")
4. Exit print("4. Exit")
ch=int(input("Enter your choice:"))
Enter your choice:3 if ch==1:
[1, 'Bikash Dash'] <--top push() # calling the push() function
================================================== print("Element Pushed")
1. Push elif ch==2:
pop_ele() # calling the pop_ele() function
2. Pop elif ch==3:
3. Display display() # calling the display() function
4. Exit elif ch==4:
Enter your choice:4 break
else:
>>> print("Sorry, You have entered invalid option")
main() # calling the main program.
ROLLING PAGE
WHITE PAGE
Q 22. . Sample Run and Output: Part B: MYSQL (5 sets of SQL queries using one/two tables)
(a) Q [22] Queries (Database Fetching records)
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M001 The Kashmir Files Action 2022/01/26 1245000 1300000 Consider the following MOVIE table and write the SQL queries based on it.
M002 Attack Action 2022/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2022/02/01 250000 300000 Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M004 Badhai Do Drama 2022/02/04 720000 68000 M001 The Kashmir Files Action 2022/01/26 1245000 1300000
M005 Shabaash Mithu Biography 2022/02/04 1000000 800000 M002 Attack Action 2022/01/28 1120000 1250000
M006 Gehraiyaan Romance 2022/02/11 1500000 120000
M007 Pushpa Action 2021/12/17 2500000 500000 M003 Looop Lapeta Thriller 2022/02/01 250000 300000
M004 Badhai Do Drama 2022/02/04 720000 68000
(b) M005 Shabaash Biography 2022/02/04 1000000 800000
Type
Mithu
Action
M006 Gehraiyaan Romance 2022/02/11 1500000 120000
Thriller
Drama M007 Pushpa Action 2021/12/17 2500000 500000
Biography
Romance a) Display all information from movie.
b) Display the type of movies.
(c) Movie_ID MovieName Total earning c) Display movieid, moviename, total_eraning by showing the business done by
M001 The Kashmir Files 2545000 the movies. Claculate the business done by movie using the sum of
M002 Attack 2370000 productioncost and businesscost.
M003 Looop Lapeta 550000
d) Display movieid, moviename and productioncost for all movies with
M004 Badhai Do 788000
M005 Shabaash Mithu 1800000 productioncost greater than 150000 and less than 1000000.
M006 Gehraiyaan 1620000 e) Display the movie of type action and Drama.
M007 Pushpa 3000000 f) Display the list of movies which are going to release in February, 2022.
Commands :
(d) Movie_ID MovieName ProductionCost a) SELECT * FROM MOVIE ;
M003 Looop Lapeta 250000 b) SELECT DISTINCT TYPE FROM MOVIE ;
M004 Badhai Do 720000 c) SELECT Movie_ID, MovieName, ProductionCost + BusinessCost “Total earning”
FROM MOVIE ;
(e) (f) MovieName d) SELECT Movie_ID , MovieName , ProductionCost FROM MOVIE
MovieName
The Kashmir Files Looop Lapeta WHERE ProductionCost >150000 AND ProductionCost < 1000000 ;
Badhai Do
Attack e) SELECT MovieName FROM MOVIE
Badhai Do Shabaash Mithu
Gehraiyaan WHERE Type =’Action’ OR Type =’Drama’ ;
Pushpa
f) SELECT MovieName FROM MOVIE
WHERE MONTH (ReleaseDate) = 2 ;
WHITE PAGE ROLLING PAGE
Q 23 . Sample Run and Output:
Q [23] Queries (Based on Functions POW() , ROUND() , SUBSTR() , CONCAT() ,
SQRT() in MySQL)
(i) POW(5,3)
125
i. Write a query to display cube of 5.
Command: SELECT POW(5,3) ;
(ii)
ROUND (563.854741, - 2)
600
ii. Write a query to display the number 563.854741 rounding off to the
next hundred.
Command: SELECT ROUND(563.854741,-2);
(iii)
SUBSTR(“Computer”,4,3)
put
iii. Write a query to display “put” from the word “Computer”.
(iv) Command: SELECT SUBSTR(“Computer”,4,3);
CONCAT(DAY(CURDATE()) , ‘.’ ,MONTH(CURDATE()) , ‘.’ , YEAR(CURDATE()))
5.2.2022
iv. Write a query to display today’s date into DD.MM.YYYY format.
(v)
SQRT(625) Command: SELECT CONCAT(DAY(CURDATE()) , ‘.’ ,MONTH(CURDATE()) , ‘.’ ,
25
YEAR(CURDATE())) ;

v. Write a query to display square root of 625.


Command: SELECT SQRT(625) ;
WHITE PAGE ROLLING PAGE
Q24. Sample Run and Output: Q [24] Queries (USE of DDL & DML Commands)

i. Create a database “Sports” and open it.


Command:
CREATE DATABASE Sports ;
USE Sports ;
ii. Create a table “TEAM” with following considerations:
(iii)
a) It should have a column TeamID for storing an integer value between 1 to 9,
which refers to unique identification of a team.
Field Type Null Key Default Extra
b) Each TeamID should have its associated name (TeamName), which should be
TeamID int(1) NO PRI NULL
a string of length not less than 10 characters.
TeamName varchar(10) YES NULL
Area varchar(10) YES NULL c) Each TeamID should have its associated region (Area), which should be a
string of length not less than 10 characters.
d) Using table level constraint, make TeamID as the primary key.
(iv) Output: Query OK, 1
row affected Command: ➔
Output: Query OK, 1 CREATE TABLE TEAM (TeamID int(1),
row affected TeamName varchar(10), primary key (teamid),
Output: Query OK, 1 Area varchar(20) ) ;
row affected iii. Show the structure of the table TEAM using a SQL statement.
Output: Query OK, 1
row affected Command: ➔ DESCRIBE TEAM ;
iv. As per the preferences of the students four teams were formed as given below.
(v) Insert these four rows in TEAM table:
TeamID TeamName Area Row 1: (1, Royal, Bihar)
1 Royal Bihar Row 2: (2, Toofan , Punjab)
2 Toofan Punjab Row 3: (3, Dream , Odisha)
3 Dream Odisha Row 4: (4, Dhoom , Rajastan)
4 Dhoom Rajastan Command:
INSERT INTO TEAM VALUES(1, ‘Royal’, ‘Bihar’);
INSERT INTO TEAM VALUES(2, ‘Toofan’, ‘Punjab’);
INSERT INTO TEAM VALUES(3, ‘Dream’, ‘Odisha’);
INSERT INTO TEAM VALUES(4, ‘Dhoom’, ‘Rajastan’);
v. Show the contents of the table TEAM using a DML statement.
• SELECT * FROM TEAM ;
WHITE PAGE ROLLING PAGE
Q25. Sample Run and Output: Q [25] Queries (USE of DDL & DML Commands)
i) Create a database StdRecord and open it.
Answers:
• CREATE DATABASE StdRecord;
• USE StdRecord;
(ii) ii) Now create a table STUDENTS and insert data as shown below. Choose
Output: Query OK, 1 appropriate data types and constraints for each attribute.
row affected StudentID StudentNM DOB Stream Class Grade Stipend
S1 Aditya Dash 2004/2/20 Humanities XII B 800
Output: Query OK, 1 S2 Sonali Kar 2003/3/21 Science XI A 950
row affected
S3 Sudipta Saha 2004/2/22 Science XII C 550
S4 Maitree Das 2005/1/23 Commerce XII B 800
Output: Query OK, 1
S5 Mohit Varma 2003/9/24 Science XI A 900
row affected
Output: Query OK, 1 S6 Gita Sahoo 2005/2/25 Humanities XII B 850
row affected S7 Reena Sharma 2003/12/25 Commerce XI C 550
Output: Query OK, 1 S8 Nikhil Hota 2004/8/15 Humanities XI C 500
row affected Commands:
Output: Query OK, 1 CREATE TABLE STUDENTS (StudentID varchar(2) NOT NULL primary key,
row affected
StudentNM varchar(25), DOB date,
Output: Query OK, 1
row affected Stream varchar(25), Class varchar(25),
Output: Query OK, 1 Grade varchar(25) CHACK(Grade IN (‘A’,‘B’,‘C’)),
row affected Stipend int(4)) ;
INSERT INTO STUDENTS VALUES(S1,‘Aditya Dash’,‘2004/2/20’,‘Humanities’,‘XII’,‘B’,800);
(iii)
INSERT INTO STUDENTS VALUES(S2,‘Sonali Kar’,‘2003/3/21’,‘Science’,‘XI’,‘A’,950);
StudentID StudentNM DOB Stream Class Grade Stipend INSERT INTO STUDENTS VALUES(S3,‘Sudipta Saha’,‘2004/2/22’,‘Science’,‘XII’,‘C’,550);
S1 Aditya Dash 2004/2/20 Humanities XII B 800 INSERT INTO STUDENTS VALUES(S4,‘Maitree Das’,‘2005/1/23’,‘Commerce’,‘XII’,‘B’,800);
S2 Sonali Kar 2003/3/21 Science XI A 950
S4 Maitree Das 2005/1/23 Commerce XII B 800
INSERT INTO STUDENTS VALUES(S5,‘Mohit Varma’,‘2003/9/24’,‘Science’,‘XI’,‘A’, 900);
S5 Mohit Varma 2003/9/24 Science XI A 900 INSERT INTO STUDENTS VALUES(S6,‘Gita Sahoo’,‘2005/2/25’,‘Humanities’,‘XII’,‘B’,850);
S6 Gita Sahoo 2005/2/25 Humanities XII B 850 INSERT INTO STUDENTS VALUES(S7,‘Reena Sharma’,‘2003/12/25’,‘Commerce’,‘XI’,‘C’,550);
INSERT INTO STUDENTS VALUES(S8,‘Nikhil Hota’,‘2004/8/15’,‘Humanities’,‘XI’,‘C’,500);
iii) Display the students record those have grade not ‘C’.
Answer: SELECT * FROM STUDENTS WHERE Grade != ’C’;
WHITE PAGE ROLLING PAGE
Q 25. Sample Run and Output: Continue……. iv) Display Name, class, stream of the students getting stipend not more than 600.
Answer: SELECT StudentNM, Class, Stream FROM STUDENTS
(iv) StudentNM Class Stream WHERE Stipend<=600;
Sudipta Saha XII Science
v) Display student’s Name, and the stipend paid to commerce students.
Reena Sharma XI Commerce
Nikhil Hota XI Humanities Answer: SELECT StudentNM, Stipend FROM STUDENTS
WHERE Stream = ‘Commerce’;
(v) (vi) vi) List out the student’s name & stipend those names starts with letter ‘M’.
StudentNM Stipend StudentNM Class Stipend
Maitree Das 800
Answer: SELECT StudentNM, Class, Stipend FROM STUDENTS
Maitree Das XII 800
Reena Sharma 550 WHERE StudentNM LIKE ‘M%’;
Mohit Varma XI 900
vii) Display maximum and minimum stipend of the students from the Table
(vii) STUDENTS.
Maximum Stipend Minimum Stipend
Answer: SELECT MAX(Stipend) “Maximum Stipend”, MIN(Stipend) “Minimum Stipend”
900 900
FROM STUDENTS;

(viii) viii) Display Total amount and average of stipend of all the students from the Table
Total Stipend Average Stipend STUDENTS.
5900 737.5 Answer: SELECT SUM(Stipend) “Total Stipend”, AVG(Stipend) “Average Stipend”
FROM STUDENTS;
(x) ix) Modify the stipend amount and increase it by 100, for all students who get
stipend less than 600.
StudentID Student NM DOB Stream Class Grade Stipend Answer: UPDATE STUDENTS SET Stipend= Stipend+100 WHERE Stipend< 600;
S1 Aditya Dash 2004/2/20 Humanities XII B 800
S6 Gita Sahoo 2005/2/25 Humanities XII B 850
x) Display the students records by ascending order of their name those have grade
S4 Maitree Das 2005/1/23 Commerce XII B 800 ‘B’ and ‘A’.
S5 Mohit Varma 2003/9/24 Science XI A 900 Answer: SELECT * FROM STUDENTS WHERE Grade =’A’ OR Grade =’B’
S2 Sonali Kar 2003/3/21 Science XI A 950
ORDER BY StudentNM;
xi) Add one column percentMark of data type decimal to the table STUDENNTS.
(xii) Stream COUNT(*)
Answer: ALTER TABLE STUDENTS ADD ( percentMark decimal);
Humanities 3
xii) Display the number of students is getting stipend more than 500 stream-wise in
Science 3
Commerce 2 table STUDENTS.
Answer: SELECT Stream , COUNT(*) FROM STUDENTS
GROUP BY Stream HAVING Stipend>500;
WHITE PAGE ROLLING PAGE
Q26. Sample Run and Output: Q [26] Consider the following tables Item & Customer. Write SQL commands &
outputs for the statement (i) to (Viii)
Table: ITEM
(i)
C_ID ItemName Manufacturer Price
PC01 Personal Computer ABC 35000
C_ID CustomerName City P_ID
LC05 Laptop ABC 55000
01 N.Roy Delhi LC03
PC03 Personal Computer XYZ 32000
12 R.Pandey Delhi PC06
PC06 Personal Computer COMP 37000
15 C.Sharma Delhi LC03
LC03 Laptop PQR 57000
(ii)
Table: CUSTOMER
C_ID CustomerName City P_ID
C_ID ItemName Manufacturer Price 01 N.Roy Delhi LC03
LC05 Laptop ABC 55000 06 H.Singh Mumbai PC03
PC01 Personal Computer ABC 35000 12 R.Pandey Delhi PC06
PC06 Personal Computer COMP 37000 15 C.Sharma Delhi LC03
16 K.Agarwalla Banglore PC01
(iii)
(i) To display the details of those Customers whose city is Delhi.
CustomerName City ItemName Price
Ans : SELECT * FROM CUSTOMER WHERE City=’Delhi’;
N.Roy Delhi Laptop r 57000
H.Singh Mumbai Personal Compute 32000 (ii) To display the details of Item whose Price is in the range of 35000 to 55000
R.Pandey Delhi Personal Computer 37000 (Both values included).
C.Sharma Delhi Laptop 57000 Ans: SELECT * FROM ITEM WHERE Price BETWEEN 35000 AND 55000 ;
K.Agarwalla Banglore Personal Computer 35000 (iii) To display the CustomerName, City from table Customer, and ItemName
and Price from table Item, with their corresponding matching I_ID.
Ans : SELECT CustomerName , City, ItemName , Price
FROM Item I , Customer C WHERE I . C_ID = C . P_ID;
(iv) To increase the Price of all Items by 1000 in the table Item.
Ans : UPDATE ITEM SET Price = Price + 1000 ;
WHITE PAGE
ROLLING PAGE
Q 26. Sample Run and Output: Continue…….
(v) (v) To display the distinct cities of Customers .
Ans: SELECT DISTINCT City FROM Customer.
Ans: City
Delhi
Mumbai (vi) To display Item name, maximum Price and number of items in the table ITEM
Bangalore according to Item name wise.

Ans: SELECT ItemName , MAX(Price), Count(*) FROM ITEM


(vi)
GROUP BY ItemName;
Ans:
ItemName Max(Price) Count(*)
(vii) To display the CustomerName from table Customer, and manufacturer
Personal Computer 37000 3 from table Item, with their corresponding matching I_ID.
Laptop 57000 2
Ans: SELECT CustomerName, Manufacturer FROM Item, Customer
(vii) WHERE Item.Item_Id=Customer.Item_Id;
Ans: (viii) To display Item name and increased price by 100 times whose manufacturer
CustomerName Manufacturer Name name is ‘ABC’ in the table Item.
N.Roy PQR
H.Singh XYZ Ans: SELECT ItemName , Price * 100 FROM Item
R.Pandey COMP WHERE Manufacturer = ‘ABC’;
C.Sharma PQR
K.Agarwal ABC

(viii)
Ans:
ItemName Price*100
Personal Computer 3500000
Laptop 5500000
WHITE PAGE ROLLING PAGE
Q27 . Sample Run and Output: Part C: Python-SQL Database Connectivity 2 Programs
Q [27] Consider the following table GARMENT as given below.
Write a python program using database connectivity to count the rows from the
Total no-of rows retrieved so far from result set:1 GARMENT table by fetchone() and fetchmany() method.
( G01, T-Shirt, XL , Red, 550 ) TABLE: GARMENT
G_ID GName Size Colour Price
Total no-of rows retrieved so far from result set :4
G01 T-Shirt XL Red 550
(G02, Jeans , L, Blue, 950 ) G02 Jeans L Blue 950
(G03, Skirt, M, White, 320 )
G03 Skirt M White 320
(G04, Kurti, XXL, Pink, 470 )
G04 Kurti XXL Pink 470
G05 Trousers L Brown 570
G06 Formal dress XL LightBlue 1250
G07 Salwar XXXL Black 1950
G08 Kids Wear M Red 650
Python Program Coding:
import mysql.connector as sqltor
mycon =sqltor.connect(host="localhost", user="root", passwd="cems@com",
database="ProductsDetail")
if mycon.is_connected()==False:
print(“Error connecting to mysql database”)
cursor = mycon.cursor()
cursor.execute(“SELECT * FROM GARMENT”)
data=cursor.fetchone()
count=cursor.rowcount
print(“Total no-of rows retrieved so far from result set:”, count)
print(data)
data=cursor.fetchmany(3)
count=cursor.rowcount
print(“Total no-of rows retrieved so far from result set:”, count)
# To display the records on the screen those are fetched by cursor.
for row in data:
print(row)
mycon.close()
WHITE PAGE ROLLING PAGE
Q28 . Sample Run and Output: 28. Consider the following table GARMENT as given below.
Write a python program using database connectivity that deletes records from
Rows affected and deleted GARMENT table of database ProductsDetail that have GName= “Salwar”.
TABLE: GARMENT
Deletion successful. G_ID GName Size Colour Price
G01 T-Shirt XL Red 550
G02 Jeans L Blue 950
G03 Skirt M White 320
G04 Kurti XXL Pink 470
G05 Trousers L Brown 570
G06 Formal dress XL LightBlue 1250
G07 Salwar XXXL Black 1950
G08 Kids Wear M Red 650
Python Program Coding:
# Delete records from the table
import mysql.connector as ctor

con = ctor.connect(host="localhost", user="root", passwd="cems@ com",


database="ProductsDetail")
cursor = con.cursor()

SQ =”DELETE FROM GARMENT WHERE GName=’Salwar’”


con.execute(SQ)

con.commit() # commit the changes in the table physically.

print(“Rows affected and deleted”)

if cursor.rowcount>0:
print(“Deletion successful.”)
else:
print(“data not fount.”)
con.close()
WHITE PAGE ROLLING PAGE
Q29. Sample Run and Output: 29. Write code to connect to a MySQL database namely School and
then fetch all those records from table Student where grade is ' A' .
(101, 'RUHANII', 76.8, 'A', 'A', 'PENDING') Table Student of MySQL database School
(103, 'SIMRAN', 81.2, 'A', 'B', 'EVALUATED')
rollno name marks grade section project
101 RUHANII 76.8 A A PENDING
102 GEOGRE 71.2 B A SUBMITTED
103 SIMRAN 81.2 A B EVALUATED
104 ALI 61.2 B C ASSIGNED
105 KUSHAL 51.6 C C EVALUATED
106 ARSIYA 91.6 A+ B SUBMITTED
107 RAUNAK 32.5 F B SUBMITTED

Python Program Coding:


import mysql.connector as mysql

db_con = mysql.connect(
host = "localhost",
user = "root",
password = "tiger",
database = "School")

cursor = db_con.cursor()

cursor.execute("SELECT * FROM Student WHERE grade = 'A'")


student_records = cursor.fetchall()

for student in student_records:


print(student)

db_con.close()
WHITE PAGE ROLLING PAGE
Q 30 . Sample Run and Output: 30. Design a Python application to obtain a search criteria from user
and then fetch records based on that from empl table.
Enter search criteria : job = 'clerk' Table: Empl
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Fetched records: 8369 SMITH CLERK 8902 1990-12-18 800 NULL 20
8499 ANYA SALESMAN 8698 1991-02-20 1600 300 30
8521 SETH SALESMAN 8698 1991-02-22 1250 500 30
(8369, 'SMITH', 'CLERK', 8902, datetime.date(1990, 12, 18), 800.0, None, 20) 8566 MAHADEVAN MANAGER 8839 1991-04-02 2985 NULL 20
8654 MOMIN SALESMAN 8698 1991-09-28 1250 1400 30
(8886, 'ANOOP', 'CLERK', 8888, datetime.date(1993, 1, 12), 1100.0, None, 20) 8698 BINA MANAGER 8839 1991-05-01 2850 NULL 30
8839 AMIR PRESIDENT NULL 1991-11-18 5000 NULL 10
(8900, 'JATIN', 'CLERK', 8698, datetime.date(1991, 12, 3), 950.0, None, 30)
8844 KULDEEP SALESMAN 8698 1991-09-08 1500 0 30
(8934, 'MITA', 'CLERK', 8882, datetime.date(1992, 1, 23), 1300.0, None, 10) 8882 SHIAVNSH MANAGER 8839 1991-06-09 2450 NULL 10
8886 ANOOP CLERK 8888 1993-01-12 1100 NULL 20
8888 SCOTT ANALYST 8566 1992-12-09 3000 NULL 20
8900 JATIN CLERK 8698 1991-12-03 950 NULL 30
8902 FAKIR ANALYST 8566 1991-12-03 3000 NULL 20
8934 MITA CLERK 8882 1992-01-23 1300 NULL 10

Python Program Coding:


import mysql.connector

db_con = mysql.connector.connect(host = "localhost",


user = "root",
passwd = "fast",
database = "employeedb")
cursor = db_con.cursor()

search_criteria = input("Enter search criteria : ")


sql1 = "SELECT * FROM EMPL WHERE {}".format(search_criteria)
cursor.execute(sql1)

records = cursor.fetchall()
print("Fetched records:")
for record in records:
print(record)

db_con.close()

You might also like