0% found this document useful (0 votes)
54 views40 pages

CS Practical File XII 2023 - 2024 Final

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)
54 views40 pages

CS Practical File XII 2023 - 2024 Final

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/ 40

Experiment No: 1

Program 1: Input any number from user and calculate factorial of a number

num = int(input("Enter any number :"))


fact = 1
n = num
while num>1:
fact = fact * num
num-=1

print("Factorial of ", n , " is :",fact)

OUTPUT

Enter any number :6


Factorial of 6 is : 720

1
Experiment No:2

Program 2: Input any number from user and check it is Prime number or not.

import math
num = int(input("Enter any number :"))
isPrime=True
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
isPrime=False

if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")

OUTPUT

Enter any number :117


## Number is not Prime ##

Enter any number :113


## Number is Prime ##

Page : 3
Experiment No: 3

Program 3: Write a code to compute the nth Fibonacci number.

def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1) + fib(n-2)

n=int(input("Enter the number"))


print("The nth Fibonacci number is ",fib(n))

Page : 4
Experiment No: 4

Program 4: Write a code to find the sum of all elements of a list.

def sum(n,l):
if l==1:
return n[0]
else:
return n[l-1]+sum(n,l-1)

n=eval(input("Enter a list"))
r=sum(n,len(n))
print("The sum is ",r)

Page : 5
Experiment No: 5

Program 5 Write a Python program to test if a string is palindrome or not.

n=int(input('Enter a number '))


copy=n
s=0
while n>0:
d=n%10
n=n//10
s=s*10+d
print('The reverse is ',s)
if s==copy:
print('Number is Palindrome')
else:
print('Number is not Palindrome')

Page : 6
Experiment No: 6

Program 6: Program to search any word in given string/sentence

def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count

str1 = input("Enter any sentence :")


word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")

OUTPUT

Enter any sentence :my computer your computer our computer everyones computer
Enter word to search in sentence :computer
## computer occurs 4 times ##

Enter any sentence :learning python is fun


Enter word to search in sentence :java
## Sorry! java not present

Page : 7
Experiment No: 7

Program 7: Program to read and display file content line by line with each
word separated by „#‟.‟

f = open("file1.txt")

for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()

NOTE : if the original content of file is:


India is my country
I love python
Python learning is fun

OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#

Page : 8
Experiment No: 8

Program 8: Program to read the content of file and display the total number
of consonants, uppercase, vowels and lower case characters.‟

f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in filE:",v)
print("Total Consonants in file:",c)
print("Total Capital letters in file:",u)
print("Total Small letters in file:",l)
print("Total Other than letters:",o)
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun
123@

OUTPUT
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in file :2
Total Small letters in file : 44
Total Other than letters :4

Page : 9
Experiment No: 9

Program 9: Program to create binary file to store Rollno and Name, Search
any Rollno and display name if Rollno found otherwise “Rollno not found”

import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'

while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()

Page : 10
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Add More ?(Y)y

Enter Roll Number :2


Enter Name :Jasbir
Add More ?(Y) N

Enter Roll number to search :2


## Name is : Jasbir ##
Search more ?(Y) :y

Enter Roll number to search :1


## Name is : Amit ##
Search more ?(Y) :y

Enter Roll number to search :3


####Sorry! Roll number not found ####
Search more ?(Y) :n

Page : 11
Experiment No: 10

Program 10: Program to create binary file to store Rollno , Name and
Marks and update marks of entered Rollno

import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()

Page : 12
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Enter Marks :99
Add More ?(Y)y

Enter Roll Number :2


Enter Name :Vikrant
Enter Marks :88
Add More ?(Y) N

Enter Roll number to update :2


## Name is : Vikrant ##
## Current Marks is : 88 ##
Enter new marks :90
## Record Updated ##
Update more ?(Y) :y

Page : 13
Experiment No: 11

Program 11: Program to read the content of file line by line and write it
to another file except for the lines contains „a‟‟ letter in it.

f1 = open("file2.txt")
f2 = open("file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully!
##”)f1.close()
f2.close()

NOTE: Content of file2.txt


a quick brown
fox one two
three four five
six seven
India is my
countryeight
nine ten
bye!

OUTPUT

## File Copied Successfully! ##

NOTE: After copy content of file2copy.txt


one two three
fourfive six
seven eight
nine ten bye!

Page : 14
Experiment No: 12

Program 12: Program to create CSV file and store empno,name,salary


and search any empno and display name,salary and if not found
appropriate message.

import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")

Page : 15
OUTPUT
Enter Employee Number 1

Enter Employee Name Amit

Enter Employee Salary :90000

## Data Saved... ##

Add More ?y

Enter Employee Number 2

Enter Employee Name Sunil

Enter Employee Salary :80000

## Data Saved... ##

Add More ? n

Enter Employee Number to search :2

============================

NAME : Sunil

SALARY : 80000

Search More ? (Y)y

Enter Employee Number to search :3

============================

EMPNO NOT FOUND

==========================

Search More ? (Y) n

Page : 16
Experiment No: 13

Program 13 Create a CSV file by entering user-id and password , read and
search the password for given user id.

import csv
with open("mail.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("mail.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")

for i in fileobj2:
next(fileobj2)

# print(i,given)
if i[0] == given:
print(i[1])
break

Page : 17
Experiment No: 14

Program 14: Program to generate random number 1-6, simulating a dice

import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break

OUTPUT

4Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n

Page : 18
Experiment No: 15

Program 15: Program to implement Stack in Python using List

def isEmpty(S):
if len(S)==0:
return True
else:
return False

def Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()

Page : 19
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break

OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10

Continue….
Page : 20
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :30

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 30 <== 20 <== 10 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :3
Top Item : 30

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :2

Deleted Item was : 30


Page : 21
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 20 <== 10 <==

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :0
Bye

Page : 22
Experiment No: 16

Program 16: Write a python program to perform to implement a stack for these
book- details(bookno,book name) just implement push and pop operations.

def push(Book):
Bno=int(input("Enter the Book number"))
Bname=input("Enter the Book's Name")
Book.append([Bno,Bname])
def pop(Book):
if Book==[]:
print("underflow")
else:
print("Book Record Deleted",Book.pop())
def display(Book):
if Book==[]:
print("underflow!!!")
else:
print("Books record in Stack\n")
top=len(Book)-1
print(Book[top],"<-top")
for i in range(top-1,-1,-1):
print(Book[i])

Book=[]
while True:
print("\n 1. Push \n 2 Pop \n 3 Display \n 4 Exit")
ch=int(input("Enter your choice"))
if ch==1:
push(Book)
elif ch==2:
pop(Book)
elif ch==3:
display(Book)
else:
break

Page : 23
Experiment No: 17

Program 17: Write a menu driven python program using function Push( ) , Pop and
Display to implement the stack . The program will store the Employee
details i.e. Employee number , Employee name and salary.

def push(Emp):
eno=int(input("Enter the Employee number"))
ename=input("Enter the Employee Name")
sal=float(input("Enter the salary"))
Emp.append([eno,ename,sal])
def pop(Emp):
if Emp==[]:
print("underflow")
else:
print("Employee Record Deleted",Emp.pop())
def display(Emo):
if Emp==[]:
print("underflow!!!")
else:
print("Employee record in Stack\n")
top=len(Emp)-1
print(Emp[top],"<-top")
for i in range(top-1,-1,-1):
print(Emp[i])

Emp=[]
while True:
print("\n 1. Push \n 2 Pop \n 3 Display \n 4 Exit")
ch=int(input("Enter your choice"))
if ch==1:
push(Emp)
elif ch==2:
pop(Emp)
elif ch==3:
display(Emp)
else:
break

Page : 24
Experiment No: 18

Program 18: Program to connect with database and store record of


Employee and display records.

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password="qmgs")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")

Page : 25
OUTPUT

0. ADD RECORD
1. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000

1. ADD RECORD
2. DISPLAY RECORD
0. EXIT

Enter Choice :0
## Bye!! ##

Page : 26
Experiment No: 19

Program 19: Program to connect with database and search employee number
in table employee and display record, if empno not found display
appropriate message.

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password="qmgs",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()if
cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")

OUTPUT

########################################
EMPLOYEE SEARCHING FORM
########################################

ENTER EMPNO TO SEARCH :1


EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 80000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found
SEARCH MORE (Y) :n

Page : 27
Experiment No: 20

Program 20: Program to connect with database and update the


employee record of entered empno.

eno = int(input("ENTER EMPNO TO UPDATE :"))


query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME",
"%15s"%"DEPARTMENT", "%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT
TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format
(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")

Page : 28
OUTPUT

########################################
EMPLOYEE UPDATION FORM
########################################

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000

## ARE YOUR SURE TO UPDATE ? (Y) :y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED ##
UPDATE MORE (Y) :y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000

## ARE YOUR SURE TO UPDATE ? (Y) :y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )SALES
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED ##
UPDATE MORE (Y) :Y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 90000

## ARE YOUR SURE TO UPDATE ? (Y) :Y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE ) 91000
## RECORD UPDATED ##
UPDATE MORE (Y) :Y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOUR SURE TO UPDATE ? (Y) :N


UPDATE MORE (Y) :N

Page : 29
Experiment No: 21

Program 21: Program to connect with database and delete the record
of entered employee number.

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password="qmgs",database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)SS
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
########################################
EMPLOYEE DELETION FORM
########################################

ENTER EMPNO TO DELETE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOUR SURE TO DELETE ? (Y) :y


=== RECORD DELETED SUCCESSFULLY! === DELETE
MORE ? (Y) :y
ENTER EMPNO TO DELETE :2
Sorry! Empno not found
DELETE MORE ? (Y) :n

Page 30
E Experiment No: 22

Program 22: Program to connect with database and store record 0f student and
display records.

import mysql.connector as mycon


con=mycon.connect(host='localhost',user='root',password="qmgs")
cur=con.cursor()
cur.execute("create database if not exists school")
cur.execute("Use school")
cur.execute("create table if not exists student(sturno int,name varchar(20),subject varchar(12),marks int)")
con.commit()
choice=None
while choice!=0:
print("1.ADD RECORD")
print("2.DISPLAY RECORD")
print("0.EXIT")
choice=int(input("Enter Choice:"))
if choice==1:
r=int(input("Enter Student Roll Number:"))
n=input("Enter Student Name:")
s=input("Enter Subject:")
m=int(input("Enter Marks:"))
query="insert into student values({},'{}','{}',{})".format(r,n,s,m)
cur.execute(query)
con.commit()
print("## Data Saved##")
elif choice==2:
query="select * from student"
cur.execute(query)
result=cur.fetchall()
print("%10s"%"StuRno","%20s"%"NAME","%15s"%"Subject","%10s"%"Marks")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("##Bye!!##")
else:
print("## INVALID CHOICE ##") Page 31
Experiment No: 23

Program 23: Program to connect with database and search student number in
table student and display record, if sturno not found display appropriate
message.
import mysql.connector as mycon
con=mycon.connect(host="localhost",user="root",password="qmgs",database="school")
cur=con.cursor()
print("#"*40)
print("Student searching form")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
sturno=int(input("Enter Student Roll number to search:"))
query="select*from student where sturno={}".format(sturno)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Sorry!student not found")
else:

print("%10s"%"StudentRollnumber","%20s"%"Name","%15s"%"subject","%10s"%"marks")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("Search more(Y):")

Page 32
Experiment No: 24
Program 24: Program to connect with database and update the student
record of entered sturno.

import mysql.connector as mycon


con=mycon.connect(host="localhost",user="root",password="qmgs",database="school")
cur=con.cursor()
print("#"*40)
print("student updation form")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
sturno=int(input("Enter Student Roll number to update:"))
query="select * from student where sturno={}".format(sturno)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Sorry!Student Roll number not found")
else:
print("%10s"%"Student Rno","%20s"%"Name","%15s"%"Subject","%10s"%"Marks")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n##Are your sure to update?(Y):")
if choice.lower()=='y':
print("==You can update only Subject and Marks==")
print("==For Sturno and name contact admin==")
d=input("Enter new subject,(Leave blank if not want to change)")
if d=="":
d=row[2]
try:
s=int(input("Enter new Marks,(Leave blank if not want to change)"))
except:
s=row[3]
query="update student set subject='{}',marks='{}'where sturno={}".format(d,s,sturno)
cur.execute(query)
con.commit()
print("##Record updated##")
ans=input("Update More(y):") Page 33
Experiment No: 25

Program 25: Program to connect with database and delete the record of
entered employee number.

import mysql.connector as mycon


con=mycon.connect(host="localhost",user="root",password="qmgs",database="school")
cur=con.cursor()
print("#"*40)
print("student deletion form")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
sturno=int(input("Enter Student roll number to delete:"))
query="select*from student where sturno={}".format(sturno)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Sorry!Student Roll number not found")
else:
print("%10s"%"StudentRoll
Number","%20s"%"Name","%15s"%"Subject","%10s"%"Marks")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n##Are your sure to delete?(y):")
if choice.lower()=='y':
query="delete from student where sturno={}".format(sturno)
cur.execute(query)
con.commit()
print("===Record deleted successfully!===")
ans=input("Delete More?(y):")

Page 34
Q26. Consider the following table named STUDENT. Write command of MySQL for (i) to (viii) and output for
(ix) and (x).
Table : STUDENT
Adno SName Marks Clsection Stream
R001 Sushant 90.2 12A Science
R002 Vaidyanath 80.5 12B Humanities
R003 Miara 68.9 12B Science
R004 Niara 96.0 12A Commerce
R005 Shinjini 88.9 12D Commerce
(i) To display all information of the students of humanities in descending order of percentage.

Ans. select * from student where stream='humanities' order by marks desc;

(ii) To display Adno, Name, Marks and Stream of those students whose name is less than 6 characters
long.

Ans. select adno, sname, marks, stream from student where length(sname) < 6;

(iii) To find the min, max, sum, and average of the marks

Ans. select min(marks), max(marks), sum(marks), avg(marks) from student;

(iv) To display the highest marks in each stream.

Ans. select stream, max(marks) from student group by stream;

(v) Display the adno, marks in descending order of the marks

Ans. select adno, marks from student order by marks desc;

(vi) To add another column Bus_Fees with datatype and size as Decimal (8,2).

Ans. alter table student add bus_fees decimal(8,2);

(vii) To increase marks by 2 of all the Humanities students.

Ans. update student set marks=marks+2 where stream='humanities';

(viii) To delete the data of Miara

Ans. delete from student where sname='Miara';

(ix) SELECT SName, Marks FROM STUDENT WHERE Name LIKE "N%";
Ans.
SName Marks
Niara 9 6.0

(x) SELECT ROUND(Marks,0) FROM STUDENT WHERE Adno="R005";


Ans.
ROUND(Marks,0)
89

Page 35
Q27. Consider the following table ‘Transporter’ that stores the order details about items to be transported.
Write SQL commands for the statements (i) to (viii) and write output for SQL queries (ix) and (x).

(i) To display names of drivers and destination city where TELEVISION is being transported.

Ans. select drivername, destination from transporter where item='television';

(ii) To display driver names and destinations where destination is not MUMBAI.

Ans. select drivername, destination from transporter where destination!='mumbai';

(iii) To display the names of destination cities where items are being transported. There should be no
duplicate values.

Ans. select distinct destination from transporter;

(iv) To display details of rows that have some value in DRIVERGRADE column.

Ans. select * from transporter where drivergrade is not null;


(v) To display names of drivers, names of items and travel dates for those items that are being transported
on or before 1st April 2019.

Ans. select drivername, item, traveldate from transporter where traveldate<= '2019-04-01';

(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.

Ans. select count(*) from transporter where drivername like '%mohan%';

(vii) To display the names of drivers, item names and travel dates in alphabetic (ascending) order of driver
names.

Ans. select drivername, item, traveldate from transporter order by drivername;

Page 36
(viii) To display names of drivers whose names are three characters long

Ans. select drivername from transporter where length(drivername)=3;

(ix) SELECT ITEM, COUNT(*) FROM TRANSPORTER GROUP BY ITEM HAVING COUNT(*) >1;

Ans.

ITEM COUNT(*)
TELEVISION 3 3
REFRIGERATOR 2 2

(x) SELECT MAX(TRAVELDATE) FROM TRANSPORTER WHERE DRIVERGRADE = ‘A’;

Ans.

MAX(TRAVELDATE)

2019-04-19

Page 37

Continue….
Q 28. Consider the following table ‘Furniture’. Write SQL commands for the statements (i) to (viii) and write
output for SQL queries (ix) and (x).

(i) To display FCODE, NAME and PRICE of items that have Price less than < 5000.

Ans. select fcode, name, price from furniture where price<5000;

(ii) To display NAMES and PRICE of those Furniture Items that have ‘table’ anywhere in their names.

Ans. select name, price from furniture where name like '%table%';

(iii) To display WCode of Furniture Items. There should be no duplicate values.

Ans. select distinct wcode from furniture;

(iv) To display the NAMES and PRICE increased by 500.00 of all the furniture items. (Price should only
be displayed as increased; there should be no increase in the data in the table)

Ans. select name, price+500 from furniture ;

(v) To display FCODE and NAME of each Furniture Item in descending order of FCODE.

Ans. select fcode, name from furniture order by fcode desc;

(vi) To display the details of all the Furniture Items which have Manufacturing date (MANUFDATE)
between 01-JAN-2016 and 15-JUN-2017 (inclusive of both the dates).

Ans. select * from furniture where manufdate between '2016-01-01' and '2017-06-15';

(vii) To display the average PRICE of all the Furniture Items, which are made of Wood with WCODE as
W02.

Ans. select avg(price) from furniture where wcode='W02';

Page 38
(viii) To display WCODE wise, WCODE and the highest price of Furniture Items.

i) select wcode, max(price) from furniture group by wcode;

(ix) SELECT SUM(PRICE) FROM Furniture WHERE WCODE=’W03’;

Ans.
SUM(PRICE)

6500

(x) SELECT COUNT(DISTINCT PRICE) FROM Furniture;

Ans.
W CODE MAX(PRICE)
W03 4000
W01 20500
W02 35000

Page 39
Continue…..
Q29. Consider the following tables PARTICIPANT and ACTIVITY and answer the questions that follow :
With reference to the above given tables, write commands in SQL for (i) to (iii).

(i) To display Activity Code along with number of participants participating in each activity (Activity
Code wise) from the table Participant.

Ans. select activitycode, count(*) from participant group by activitycode;

(ii) To display Names of Participants, Activity Code, Activity Name in alphabetic ascending order of
names of participants.

Ans. select name, A.activitycode, activityname from participant A, activity B where A.activitycode = B.activitycode
order by name ;

(iii) To display Names of Participants along with Activity Codes and Activity Names for only those
participants who are taking part in Activities that have ‘bag’ in their Activity Names and Points of
activity are above 250.

Ans. select name, A.activitycode, activityname from participant A, activity B where A.activitycode = B.activitycode
and activityname like '%bag%' and points>250;

Page 40
Continue…..
Q. 30 Create a database “Pract2022” and make table “Worker” and “Dept” as per the details given
below:-
Table: WORKER
WID WNAME JOB SALARY DNO
1001 KANAK JAIN CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
1005 RAM CLERK 14000 D03

Table: DEPT
DNO DNAME LOCATION MANAGER
D01 PRODUCTION GROUND FLOOR SHREYA
D02 ACCOUNTS 1ST FLOOR PRANSHU
D03 SALARY 1ST FLOOR KHUSHI

Q. 1 Display Worker ID, WName and Job who are working under SHREYA
Ans Select WID , WName , Job
From Worker , Dept
Where Worker.Dno = Dept.Dno and Manager = “Shreya”;

Q. 2 Display Worker name and their respective department names who are working as ELCTRICIAN.
Ans. Select WName , DName
From Worker , Dept
Where Worker.Dno = Dept.Dno and Job=”Electrician”;

Q. 3 Display Worker name, Job and their respective manager.


Ans. Select Wname , Job , Manager
From Worker , Dept
Where Worker.Dno = Dept.Dno;
Q. 4 SELECT MIN(SALARY) FROM WORKER.
Ans.
Salary

8000

Q. 5 SELECT COUNT(DISTINCT JOB) FROM WORKER.


Ans.
Job

Page 41

You might also like