0% found this document useful (0 votes)
20 views48 pages

Solved Cs Practical List For Class Xii 2024 - 25

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)
20 views48 pages

Solved Cs Practical List For Class Xii 2024 - 25

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

KV LUMDING VKV:2024_25

COMPUTER SCIENCE (083)


PRACTICAL REPORT FILE

1
KV LUMDING VKV:2024_25

PROGRAM 1: Write a program in python of Random Number generator 1 to 6 after throwing dice.

CODE:

import random
print("Do you want to play game with dice, if yes, press 'y' otherwise any character")
ch=input()
if ch=='y' or ch=='Y':
while ch=='y' or ch=='Y' :
n=random.randint(1,6)
print("Your dice has ", n , " number")
print("Do you want to throw dice again, If yes then please type 'y', otherwise type any character ")
ch=input()
else:
print("Sorry you are not interested to play game with dice")
print("Have a nice day")

OUTPUT:

Do you want to play game with dice, if yes, press 'y' otherwise any character
y
Your dice has 5 number
Do you want to throw dice again, If yes then please type 'y', otherwise type any character
y
Your dice has 5 number
Do you want to throw dice again, If yes then please type 'y', otherwise type any character
y
Your dice has 2 number
Do you want to throw dice again, If yes then please type 'y', otherwise type any character

2
KV LUMDING VKV:2024_25

PROGRAM 2: Write a program in python to calculate a to the power b through function.

CODE:

def atothepowerb(m,n):
p=1
for i in range(1,n+1):
p=p*m
return p

a=int(input("Enter any value as a base number"))


b=int(input("Enter any value as a power of the base number"))
x=atothepowerb(a,b)
print("Caluculated value of ",a, " to the power ",b, " = ", x)

OUTPUT:

Enter any value as a base number5


Enter any value as a power of the base number3
Caluculated value of 5 to the power 3 = 125

3
KV LUMDING VKV:2024_25

PROGRAM 3: Write a program in python to calculate factorial of a number through function.

CODE:

def factorial(x):
fact=1
for i in range(1,x+1):
fact=fact*i
return fact

n=int(input("Enter any number whose factorial you want to calculate: "))


f=factorial(n)
print("Calculated factorial value of the number ",n, " is: ", f)

OUTPUT:

Enter any number whose factorial you want to calculate: 5


Calculated factorial value of the number 5 is: 120

4
KV LUMDING VKV:2024_25

PROGRAM 4: Write a program in python to print Fibonacci series upto nth terms and its sum through
function.

CODE:

def fibo_series(m):
if m==1:
print(0,end=" ")
elif m==2:
print(0,1,end=" ")
else:
f,s=0,1
print(f,s,end=" ")
for i in range(3,n+1):
t=f+s
print(t,end=" ")
f=s
s=t
def fibo_sum(m):
if m==1:
return 0
elif m==2:
return 1
else:
fsum=1
f,s=0,1
for i in range(3,n+1):
t=f+s
fsum=fsum+t
f=s
s=t
return fsum
n=int(input("Enter number of terms for which you want to display the fibonacii series="))
print("The fibonacii series is:",end=" ")
fibo_series(n)
print("\nThe sum of fibonacii series upto ", n , " terms=", fibo_sum(n))
OUTPUT:

Enter number of terms for which you want to display the fibonacii series=8
The fibonacii series is: 0 1 1 2 3 5 8 13
The sum of fibonacii series upto 8 terms= 33

5
KV LUMDING VKV:2024_25

PROGRAM 5: Write a program in python to search & display an element in a list by binary search
technique through function.

CODE:

def bsearch(list,n):
beg=0
last=len(list)-1

while beg<=last:
mid=(beg+last)//2
if n==list[mid]:
return mid
elif n>list[mid]:
beg=mid+1
elif n<list[mid]:
last=mid-1
else:
return -1

L=eval(input("Enter a list of integer values"))


num=int(input("Enter the number to find in a list"))
index=bsearch(L,num)
if index<0:
print("Sorry!!!, Number not found in this list")
else:
print("The value at index=",index)
OUTPUT:

Enter a list of integer values[20,50,60,70,90,100,120]


Enter the number to find in a list100
The value at index= 5

Enter a list of integer values[20,50,60,70,90,100,120]


Enter the number to find in a list95
Sorry!!!, Number not found in this list

6
KV LUMDING VKV:2024_25

PROGRAM 6: Write a program in python to computer GCD(greatest common divisor) of two number
through function.

CODE:

def gcd(x,y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd

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


b=int(input("Enter second number:"))
g=gcd(a,b)
print("GCD of numbers ", a, " and " , b, "is ", g)

OUTPUT:
Enter first number:5
Enter second number:15
GCD of numbers 5 and 15 is 5

Enter first number:7


Enter second number:17
GCD of numbers 7 and 17 is 1

7
KV LUMDING VKV:2024_25

PROGRAM 7: Write a program in python to check whether user entered string is palindrome or not
through function.

CODE:

def backward(string,n):
rstring=""
for i in range(n-1,-1,-1):
rstring+=string[i]
if rstring==string:
print("Entered String ",string, " is palindrome")
else:
print("Entered String ",string, " is not palindrome")

s=input("Enter a string=")
backward(s,len(s))

OUTPUT:

Enter a string=nitin
Entered String nitin is palindrome

Enter a string=kvner
Entered String kvner is not palindrome

8
KV LUMDING VKV:2024_25

PROGRAM 8 : Write a program/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.
Example: Sample input data of the list, Arr=[10,20,30,40,12,11], n=2
Output : Arr=[30,40,12,11,10,20]
CODE:

def Lshift(Arr, n):


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(Arr)
A=eval(input("Enter a list ="))
ns=int(input("Enter the place from where you want to shift element left="))
Lshift(A,ns)

OUTPUT:

Enter a list =[10,20,30,40,50,60,70,80]


Enter the place from where you want to shift element left=3
[40, 50, 60, 70, 80, 10, 20, 30]

9
KV LUMDING VKV:2024_25

PROGRAM 9 : Write a program/function which takes two lists are arguments and returns a list which
contains only the elements that are common between both lists in ascending order. Make
sure your program works on two lists of different sizes without duplicates.
Example: L1=[10,20,30,40,12,11] , L2=[20,30,40,11,15,78,60,90,100]
Output : Arr=[11,20,30,40]
CODE:

def Lshift(Arr, n):


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(Arr)
A=eval(input("Enter a list ="))
ns=int(input("Enter the place from where you want to shift element left="))
Lshift(A,ns)

OUTPUT:

Enter First List=[2,10,3,4,9,11,46]


Enter Second List=[3,4,7,9,46,11]
List with Common elements and sorted of two lists=
[3, 4, 9, 11, 46]

10
KV LUMDING VKV:2024_25

PROGRAM 10 : Write a function called letter_freq(mylist) that takes one parameter, a list of
strings(mylist) and returns a dictionary where the keys are the letters from mylist and the
values are the number of times that letter appears in the mylist e.g. if the passed list is as:
wlist=list(“aaaaabbbbcccdde”), then it should return a dictionary as
[‘a’ : 5, ’b’ : 4 , ’c’ : 3 , ’d’ : 2 , ’e’:1 ]

CODE:

def letter_freq(mylist):
d={}
for i in mylist:
if i not in d:
d[i]=mylist.count(i)
return d
wlist=list(input("Enter a string="))
rd=letter_freq(wlist)
print(rd)

OUTPUT:
Enter a string=anccddab
{'a': 2, 'n': 1, 'c': 2, 'd': 2, 'b': 1}

11
KV LUMDING VKV:2024_25

PROGRAM 11: Write a function called rem_keys(D, keylist) that accepts two parameters: a dictionary
called D and a list called keylist. Function rem_keys(D, keylist) should remove all the keys
contained in the passed keylist from the dictionary D and return the dictionay.

CODE:

def rem_keys(D, keylist):


for k in keylist:
if k in D:
del D[k]
return D

D=eval(input("Enter a dictionary="))
keys=eval(input("Enter keys to delete from dictionay="))
print("Original dictionary :", D)
print("The keylist=", keys)
print("Dictionary after removing keys:", rem_keys(D, keys))

OUTPUT:

Enter a dictionary={'a':1,'c':3,'f':6,'g':8}
Enter keys to delete from dictionay=['c','g']
Original dictionary : {'a': 1, 'c': 3, 'f': 6, 'g': 8}
The keylist= ['c', 'g']
Dictionary after removing keys: {'a': 1, 'f': 6}

12
KV LUMDING VKV:2024_25

PROGRAM 12: Write a Python program/function to count the number of strings where the string length
is 2 or more and the first and last character are same from a given list of strings.

CODE:

def countwords_gelen2(listofwords):
count = 0
for word in listofwords:
if len(word) > 1 and word[0]==word[-1]:
count += 1
return count

listwords=eval(input("Input a list of words="))


total=countwords_gelen2(listwords)
print("Total number of words having length greater than 1 and first & last character same=",total)

OUTPUT:

Input a list of words=["hello","hi","kanak", "nitin", "veer"]


Total number of words having length greater than 1 and first & last character same= 2

13
KV LUMDING VKV:2024_25

PROGRAM 13: Write a Python program/function to input a list of numbers and swap elements at the
even location with the elements at the odd locations.

CODE:

def swapevenoddloc(L):
s=len(L)
if s%2!=0:
s=s-1
for i in range(0,s,2):
L[i],L[i+1]=L[i+1],L[i]
return L
List=eval(input("Enter a list="))
slist=swapevenoddloc(List)
print("New List after swapping even odd location values=", slist)

OUTPUT:

Enter a list=[10,20,30,40,50,60]
New List after swapping even odd location values= [20, 10, 40, 30, 60, 50]

Enter a list=[10,20,30,40,50,60,70]
New List after swapping even odd location values= [20, 10, 40, 30, 60, 50, 70]

14
KV LUMDING VKV:2024_25

PROGRAM 14: Write a program in python to write a paragraph in a text file “STUDENT1.TXT” and then
display its content.

CODE:

def writelines():
f=open("STUDENT1.TXT",'w')
n=int(input("Enter how many lines want to write:"))
for i in range(n):
s=input("Enter a line=")
f.write(s+"\n")
f.close()
def readcontents():
f=open("STUDENT1.TXT",'r')
print("\n Content of this file :")
for i in f:
print(i,end="")
f.close()

writelines()
readcontents()

OUTPUT:

Enter how many lines want to write:4


Enter a line=This is my school.
Enter a line=I studied here upto class XII.
Enter a line=I enjoyed my schooling.
Enter a line=I topped in class X & XII in year 2018 and 2020 respectively.

Content of this file :


This is my school.
I studied here upto class XII.
I enjoyed my schooling.
I topped in class X & XII in year 2018 and 2020 respectively.

15
KV LUMDING VKV:2024_25

PROGRAM 15: Write a program in python to Read a text file “STUDENT1.TXT”.

CODE:

f=open(" STUDENT1.TXT",'r')
s1=f.readlines()
print(s1)
print()
for i in s1:
print(i,end="")
f.close()

OUTPUT:

['This is my school.\n', 'I studied here upto class XII.\n', 'I enjoyed my schooling.\n', 'I topped in class X & XII
in year 2018 and 2020 respectively.\n']

This is my school.
I studied here upto class XII.
I enjoyed my schooling.
I topped in class X & XII in year 2018 and 2020 respectively.

16
KV LUMDING VKV:2024_25

PROGRAM 16: Write a program in python to count & display number of character present in a text file
“STUDENT1.TXT”.

CODE:

f=open("STUDENT1.TXT ",'r')
c=0
s=f.read()
for i in s:
print(i,end="")
c=c+1

print("Total number of characters=", c)


f.close()

OUTPUT:

This is my school.
I studied here upto class XII.
I enjoyed my schooling.
I topped in class X & XII in year 2018 and 2020 respectively.
Total number of characters= 136

17
KV LUMDING VKV:2024_25

PROGRAM 17: Write a program in python to count & display number of words present in a text file
“STUDENT1.TXT”.

CODE:

f=open("STUDENT1.TXT ",'r')
c=0
s=f.readlines()
for i in s:
j=i.split()
print(j)
for k in range(len(j)):
c=c+1
print("Total number of words=", c)
f.close()

OUTPUT:

['This', 'is', 'my', 'school.']


['I', 'studied', 'here', 'upto', 'class', 'XII.']
['I', 'enjoyed', 'my', 'schooling.']
['I', 'topped', 'in', 'class', 'X', '&', 'XII', 'in', 'year', '2018', 'and', '2020', 'respectively.']
Total number of words= 27

OR

f=open("STUDENT1.TXT",'r')
c=0
s=f.read()
low=s.split()
print(low)
for i in low:
c=c+1
print("Total number of words=", c)
f.close()

OUTPUT:
['This', 'is', 'my', 'school.', 'I', 'studied', 'here', 'upto', 'class', 'XII.', 'I', 'enjoyed', 'my', 'schooling.', 'I', 'topped',
'in', 'class', 'X', '&', 'XII', 'in', 'year', '2018', 'and', '2020', 'respectively.']
Total number of words= 27

18
KV LUMDING VKV:2024_25

PROGRAM 18: Write a program in python to count & display number of lines present in a text file
“STUDENT1.TXT”.

CODE:

f=open("STUDENT1.TXT",'r')
s1=f.readlines()
print(s1)
c=0
for i in s1:
c+=1
print("Number of lines=",c)
f.close()

OUTPUT:

['This is my school.\n', 'I studied here upto class XII.\n', 'I enjoyed my schooling.\n', 'I topped in class X & XII
in year 2018 and 2020 respectively.\n']
Number of lines= 4

OR

f=open(“STUDENT1.TXT",'r')
c=0
for i in f:
print(i,end="")
c+=1
print("Number of lines=",c)
f.close()

OUTPUT:

This is my school.
I studied here upto class XII.
I enjoyed my schooling.
I topped in class X & XII in year 2018 and 2020 respectively.
Number of lines= 4

19
KV LUMDING VKV:2024_25

PROGRAM 19: Write a program in python to read a text file “STUDENT1.TXT” line by line and display
each word separated by a #.

CODE:

f=open(“STUDENT1.TXT",'r')
for i in f:
wl=i.split()
for j in wl:
print(j+"#",end="")
print()
f.close()

OUTPUT:

This#is#my#school.#
I#studied#here#upto#class#XII.#
I#enjoyed#my#schooling.#
I#topped#in#class#X#&#XII#in#year#2018#and#2020#respectively.#

20
KV LUMDING VKV:2024_25

PROGRAM 20: Write a program in python to read a text file “STUDENT1.TXT” and display the number of
vowels/ consonants/uppercase/ lowercase characters in the file.

CODE:

f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\PRACTICAL PROGRAM CLASS XII


2020_21\STUDENT1.TXT",'r')
s=f.read()
print(s)
cv=0
cc=0
cl=0
cu=0
for i in s:
if i.isalpha():
if i.islower():
cl+=1
if i in ['a','e','i','o','u']:
cv+=1
else:
cc+=1
else:
cu+=1
if i in['A','E','I','O','U']:
cv+=1
else:
cc+=1
print("No. of vowels=",cv)
print("No. of consonents=",cc)
print("No. of lowercase letters=",cl)
print("No. of uppercase letters=",cu)

f.close()

OUTPUT:

This is my school.
I studied here upto class XII.
I enjoyed my schooling.
I topped in class X & XII in year 2018 and 2020 respectively.

No. of vowels= 37
No. of consonents= 59
No. of lowercase letters= 85
No. of uppercase letters= 11

21
KV LUMDING VKV:2024_25

PROGRAM 21: Write a program in python to write roll number, name , subject and marks of students of
a class (get input from user) and store these details in a file called “STUDENT1.DAT”.

CODE:

import pickle
f=open("student1.dat",'wb')
n=int(input("Enter how many Records you want to write:"))
for i in range(n):
roll=int(input("Enter roll number of student="))
name=input("Enter name of student=")
subject=input("Enter subject=")
marks=int(input("Enter marks out of 100 in this subject="))
record=str(roll)+" "+name+" "+subject+" "+str(marks)
pickle.dump(record+ "\n", f)
f.close()

OUTPUT:

Enter how many Records you want to write:3


Enter roll number of student=1
Enter name of student=Abhay Kumar
Enter subject=Computer Science
Enter marks out of 100 in this subject=86
Enter roll number of student=2
Enter name of student=Astitva Jaiswal
Enter subject=Computer Science
Enter marks out of 100 in this subject=92
Enter roll number of student=3
Enter name of student=Abhay Kumar
Enter subject=Mathematics
Enter marks out of 100 in this subject=76

22
KV LUMDING VKV:2024_25

PROGRAM 22: Write a program in python to display the contents present in a binary file
“STUDENT1.DAT”.

CODE:

import pickle
f=open("student1.dat",'rb')
try :
s=" "
while s:
s=pickle.load(f)

print(s,end="")
except EOFError :
pass
f.close()

OUTPUT:

1 Abhay Kumar Computer Science 86


2 Astitva Jaiswal Computer Science 92
3 Abhay Kumar Mathematics 76

23
KV LUMDING VKV:2024_25

PROGRAM 23: A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
Write a user defined function CreateFile() to input data for a record and add to Book.dat
binary file.

CODE:

import pickle
f=open(“BOOK.DAT","wb")
ch='y'
while ch in "yY":
BookNo=int(input("Enter Book Number="))
BookName=input("Enter Book Name=")
Author=input("Enter Author Name=")
Price=float(input("Enter Price of the Book="))
Bookrecord=[BookNo,BookName,Author,Price]
pickle.dump(Bookrecord, f)
ch=input("Enter y or Y to add more book record, otherwise press any other character")
f.close()

OUTPUT:

Enter Book Number=1201


Enter Book Name=PHYSICS
Enter Author Name=NCERT
Enter Price of the Book=255
Enter y or Y to add more book record, otherwise press any other characterY
Enter Book Number=1202
Enter Book Name=COMPUTER SCIENCE
Enter Author Name=SUMITA ARORA
Enter Price of the Book=595
Enter y or Y to add more book record, otherwise press any other characterY
Enter Book Number=1203
Enter Book Name=CHEMISTRY
Enter Author Name=NCERT
Enter Price of the Book=260
Enter y or Y to add more book record, otherwise press any other characterN

24
KV LUMDING VKV:2024_25

PROGRAM 24:
A binary file “STUDENT.DAT” has structure (Admission_Number, Name, Percentage).
(i) Write a function writerec() to input data of the students and add to a binary file “STUDENT.DAT”.
(ii) Write a function countrec() in Python that would read contents of the file “STUDENT.DAT” and
display the details of those students whose percentage is above 75.

CODE:

def writerec():
f=open(" STUDENT.DAT","wb")
ch='y'
while ch in "yY":
Admission_Number=int(input("Enter Admission Number="))
Name=input("Enter Student Name=")
Percentage=float(input("Enter Student percentage="))
StudentRecord=(Admission_Number,Name,Percentage)
pickle.dump(StudentRecord, f)
ch=input("Enter y or Y to add more book record, otherwise press any other character")
f.close()

def countrec():
f=open(" STUDENT.DAT","rb")
count=0
try:
while True:
srecord=pickle.load(f)
if srecord[2]>75:
count+=1
print(srecord)

except EOFError:
f.close()
print("Total number of students whose percentage are greater than 75%= ",count)

writerec()
countrec()

OUTPUT:

Enter Admission Number=1001


Enter Student Name=ASTITVA
Enter Student percentage=98
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1002
Enter Student Name=GAURAVI
Enter Student percentage=99
Enter y or Y to add more book record, otherwise press any other characterY

25
KV LUMDING VKV:2024_25
Enter Admission Number=1003
Enter Student Name=MAHIMA
Enter Student percentage=65
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1004
Enter Student Name=SAURYA
Enter Student percentage=71
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1005
Enter Student Name=AMIT
Enter Student percentage=86
Enter y or Y to add more book record, otherwise press any other characterN
(1001, 'ASTITVA', 98.0)
(1002, 'GAURAVI', 99.0)
(1005, 'AMIT', 86.0)
Total number of students whose percentage are greater than 75%= 3

26
KV LUMDING VKV:2024_25

PROGRAM 25: Write a program in python that would read contents from file “STUDENT1.DAT” and
creates a file named “STUDENT3.DAT” copying only those records from “STUDENT1.DAT”
where the student name is user entered name.

CODE:

import pickle
f2=open("student1.dat","rb")
f3=open("student3.dat","wb")
uen=input("Enter complete student name for copying record=")
uen=uen.lower()
try :
s=" "
while s:
s=pickle.load(f2)
s1=s.lower()
if uen in s1:
pickle.dump(s,f3)
except EOFError :
pass
f2.close()
f3.close()

print("The data after writing record in student3.dat is:")


f4=open("student3.dat","rb")
try:
s1=" "
while s1:
s1=pickle.load(f4)
print(s1,end="")

except EOFError:
pass

f4.close()

OUTPUT:

Enter complete student name for copying record=abhay kumar


The data after writing record in student3.dat is:
1 Abhay Kumar Computer Science 86
3 Abhay Kumar Mathematics 76

27
KV LUMDING VKV:2024_25

PROGRAM 26: Write a program in python that writes the records on “STUDENT4.DAT” and update the
marks of the user entered student.
CODE:
import pickle
f=open("student4.dat",'wb')
n=int(input("Enter how many Records you want to write:"))
for i in range(n):
roll=int(input("Enter roll number of student="))
name=input("Enter name of student=")
subject=input("Enter subject=")
marks=int(input("Enter marks out of 100 in this subject="))
record=[roll,name,subject,marks]
pickle.dump(record,f)
f.close()
f1=open("student4.dat",'rb+')
print("READING FILE")
sname=input("Name the student whose marks you want to update=")
new_marks=int(input("Enter new marks="))
f1.seek(0)
try :
while True:
rpos=f1.tell()
s=pickle.load(f1)
if s[1]==sname:
print("Old details of student=", s)
s[3]=new_marks
f1.seek(rpos)
pickle.dump(s,f1)
print("New updated details of this student=", s)
except EOFError :
pass
f1.close()
OUTPUT:
Enter how many Records you want to write:2
Enter roll number of student=1
Enter name of student=abhay
Enter subject=cs
Enter marks out of 100 in this subject=85
Enter roll number of student=2
Enter name of student=astitva
Enter subject=cs
Enter marks out of 100 in this subject=90
READING FILE
Name the student whose marks you want to update=abhay
Enter new marks=92
Old details of student= [1, 'abhay', 'cs', 85]
New updated details of this student= [1, 'abhay', 'cs', 92]

28
KV LUMDING VKV:2024_25

PROGRAM 27: Write a program in python to perform write & read operation with players.csv file.

CODE:
import csv
#Code for writing data on csv file
persons=eval(input("Enter a list of tuples so that each tuple will be a row of CSV file"))
csvfile=open('players.csv','w', newline='')
obj=csv.writer(csvfile)
for person in persons:
obj.writerow(person)
csvfile.close()

#Code for reading csv file


csvfile=open('players.csv','r', newline='')
obj=csv.reader(csvfile)
for row in obj:
print (row)
csvfile.close()

OUTPUT:

Enter a list of tuples so that each tuple will be a row of CSV file
[(1,"Sachin",20000),(2,"Saurabh",15000),(3,"Rahul",18000),(4,"Azharuddin",16000),(5,"Ravindra",10500)]
['1', 'Sachin', '20000']
['2', 'Saurabh', '15000']
['3', 'Rahul', '18000']
['4', 'Azharuddin', '16000']
['5', 'Ravindra', '10500']

OUTPUT: In Notepad

29
KV LUMDING VKV:2024_25

PROGRAM 28: Write a function/program in python that reads a csv file “players.csv” and creates
another csv file “seniorplayers.csv with same contents except those players whose salary
is greater than and equal to 15000.

CODE:

import csv
rcsvfile=open('players.csv','r', newline='')
wcsvfile=open('seniorplayers.csv','w', newline='')
robj=csv.reader(rcsvfile)
wobj=csv.writer(wcsvfile)

#Writing records whose salary >=15000 from playes.csv to seniorplayers.csv


print("Records in players csv file")
for record in robj:
print(record)
if int(record[2])>=15000:
wobj.writerow(record)
rcsvfile.close()
wcsvfile.close()

#Records in seniorplayers csv file


csvfile=open('seniorplayers.csv','r', newline='')
obj=csv.reader(csvfile)
print("Records in seniorplayers")
for row in obj:
print(row)
csvfile.close()

OUTPUT:

Records in players csv file


['1', 'Sachin', '20000']
['2', 'Saurabh', '15000']
['3', 'Rahul', '18000']
['4', 'Azharuddin', '16000']
['5', 'Ravindra', '10500']
Records in seniorplayers
['1', 'Sachin', '20000']
['2', 'Saurabh', '15000']
['3', 'Rahul', '18000']
['4', 'Azharuddin', '16000']

30
KV LUMDING VKV:2024_25

PROGRAM 29: Write a program in python to implement Stack through linear list.

CODE:

stack=[]
print("Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit")
choice=int(input("Enter you choice"))
while choice in [1,2,3]:
if choice==1:
element=input("Enter the element you want to push=")
stack.append(element)
elif choice==2:
if len(stack)==0:
print("Stack is empty, deletion is impossible")
else:
ditem=stack.pop()
print("Deleted item=", ditem)
elif choice==3:
if len(stack)==0:
print("There is no element in the Stack, Excuse Me..")
else:
print("The elements in the stack=")
for i in range(-1,-len(stack)-1,-1):
print(stack[i])
elif choice==4:
exit()
print("Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit")
choice=int(input("Enter you choice"))

OUTPUT:

Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=10
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=20
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=30
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice3
The elements in the stack=
30
20
10

31
KV LUMDING VKV:2024_25

Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice2
Deleted item= 30
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice3
The elements in the stack=
20
10
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice2
Deleted item= 20
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice3
The elements in the stack=
10
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice4

32
KV LUMDING VKV:2024_25

PROGRAM 30:
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 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

CODE:

sd={}
stack=[]
def addindict():
for i in range(6):
name=input("Enter name of student=")
marks=int(input("Enter marks out of 100="))
sd[name]=marks
print("Dictionary Elements are=")
print(sd)
def pushkeys():
for key in sd:
if sd[key]>75:
stack.append(key)
def popkeys():
if stack==[]:
print("Underflow, can't delete keys")
else:
delkey=stack.pop()
print("Deleted key =",delkey)

addindict()
pushkeys()
print("Stack elements are=")
for i in stack[::-1]:
print(i)
popkeys()
print("Stack elements are=")
for i in stack[::-1]:
print(i)

OUTPUT:
Enter name of student=MAHESH
Enter marks out of 100=86
Enter name of student=SURESH
Enter marks out of 100=65

33
KV LUMDING VKV:2024_25
Enter name of student=MAHIMA
Enter marks out of 100=96
Enter name of student=RAJA
Enter marks out of 100=79
Enter name of student=MANISH
Enter marks out of 100=91
Enter name of student=RAJU
Enter marks out of 100=74
Dictionary Elements are=
{'MAHESH': 86, 'SURESH': 65, 'MAHIMA': 96, 'RAJA': 79, 'MANISH': 91, 'RAJU': 74}
Stack elements are=
MANISH
RAJA
MAHIMA
MAHESH
Deleted key = MANISH
Stack elements are=
RAJA
MAHIMA
MAHESH

34
KV LUMDING VKV:2024_25

PROGRAM 31: Write a program to create a table in mysql database through python program.

CODE:

import mysql.connector as mc
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
if mco.is_connected():
print("Yes")
else:
print("NO")
co=mco.cursor()
c="create table if not exists temp5(sl int, sname varchar(20))"
co.execute(c)
mco.commit()
print("Table created")
mco.close()

OUTPUT:
Yes
Table created

35
KV LUMDING VKV:2024_25

PROGRAM 32: Write a program to insert data in mysql database through python program.

CODE:

import mysql.connector as mc
def insertdata():
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
co=mco.cursor()
sno=int(input("Enter serial number of the student="))
sname=input("Enter name=")
ituple="insert into temp1(sl,sname) values({0},'{1}')".format(sno,sname)
co.execute(ituple)
mco.commit()
print("Record Inserted")
mco.close()

char='y'
while char=='y' or char=='Y':
insertdata()
char=input("Do you want to insert more tuples, y for yes, n for no")

OUTPUT:

Enter serial number of the student=7


Enter name=DINESH
Record Inserted
Do you want to insert more tuples, y for yes, n for noN

36
KV LUMDING VKV:2024_25

PROGRAM 33: Write a program to display all tuples in mysql database through python program.

CODE:

import mysql.connector as mc
def selectalldata():
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
co=mco.cursor()
ftuple="select * from temp1"
co.execute(ftuple)
data=co.fetchall()
for i in data:
print(i)
#mco.commit()
mco.close()

selectalldata()

OUTPUT:

(1, 'PIYUSH')
(2, 'MOHAN')
(3, 'SHIVANI')
(5, 'AYUSHI')
(6, 'SIMRAN')
(4, 'ALOK')
(7, 'DINESH')

37
KV LUMDING VKV:2024_25

PROGRAM 34: Write a program to display selected tuples in mysql database through python program.

CODE:

import mysql.connector as mc
def selectdatawithid():
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
co=mco.cursor()
serial=int(input("Enter serial number="))
ftuple="select * from temp1 where sl={}".format(serial)
co.execute(ftuple)
data=co.fetchall()
print(data)
mco.close()

selectdatawithid()

OUTPUT:

Enter serial number=6


[(6, 'SIMRAN')]

38
KV LUMDING VKV:2024_25

PROGRAM 35: Write a program to modify selected tuples in mysql database through python program.

CODE:

import mysql.connector as mc
def updatedata():
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
co=mco.cursor()
oldname=input("Enter old name=")
newname=input("Enter new name=")
updatename="update temp1 set sname='{}' where sname='{}'".format(newname,oldname)
co.execute(updatename)
mco.commit()
# TO diplay all records after updation
print("Record updated/modified")
co.execute("select * from temp1")
data=co.fetchall()
for i in data:
print(i)
mco.close()
updatedata()

OUTPUT:

Enter old name=SHIVAY


Enter new name=SHIVA
Record updated/modified
(1, 'PRIYANSHU')
(2, 'MOHANTY')
(3, 'SHIVA')
(5, 'AYUSHI')
(6, 'SIMRAN')
(4, 'ALOK')
(7, 'DINESH')

39
KV LUMDING VKV:2024_25

PROGRAM 36: Write a program to delete selected tuples in mysql database through python program.

CODE:

import mysql.connector as mc
def deletedata():
mco=mc.connect(host="localhost",user="root",passwd="password",database="kvlmg",port="3306")
co=mco.cursor()
deletesldata=int(input("Enetr the serial number whose data you want to delete="))
ddata="delete from temp1 where sl={}".format(deletesldata)
co.execute(ddata)
mco.commit()
# TO diplay all records after updation
print("Record deleted")
co.execute("select * from temp1")
data=co.fetchall()
for i in data:
print(i)
mco.close()

deletedata()

OUTPUT:

Enetr the serial number whose data you want to delete=7


Record deleted
(1, 'PRIYANSHU')
(2, 'MOHANTY')
(5, 'AYUSHI')
(6, 'SIMRAN')
(4, 'ALOK')

40
KV LUMDING VKV:2024_25

SQL QUERIES

 Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY, HAVING

Query 1:
Display the name of departments. Each department should be displayed once.
Sql Command:
SELECT DISTINCT(Dept)
FROM EMPLOYEE;

Query 2:
Find the name and salary of those employees whose salary is between 35000 and 40000.
Sql Command:
SELECT Ename, salary
FROM EMPLOYEE
WHERE salary BETWEEN 35000 AND 40000;

Query 3:
Find the name of those employees who live in guwahati, surat or jaipur city.
Sql Command:
SELECT Ename, city
FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);

Query 4:
Display the name of those employees whose name starts with ‘M’.
Sql Command:
SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;

Query 5:
List the name of employees not assigned to any department.
Sql Command:
SELECT Ename
FROM EMPLOYEE
WHERE Dept IS NULL;

Query 6:
Display the list of employees in descending order of employee code.
Sql Command:
SELECT *
FROM EMPLOYEE
ORDER BY ecode DESC;
Query 7:
Find the average salary at each department.

41
KV LUMDING VKV:2024_25

Sql Command:
SELECT Dept, AVG(salary)
FROM EMPLOYEE
GROUP BY Dept;

Query 8:
Find maximum salary of each department and display the name of that department which
has maximum salary more than 39000.
Sql Command:
SELECT Dept, MAX(salary)
FROM EMPLOYEE
GROUP BY Dept
HAVING salary > 39000;

 Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )

Query 1:
Find the average salary of the employees in employee table.
Sql Command:
SELECT AVG(salary)
FROM EMPLOYEE;

Query 2:
Find the minimum salary of a female employee in EMPLOYEE table.
Sql Command:
SELECT Ename, MIN(salary)
FROM EMPLOYEE
WHERE sex=’F’;

Query 3:
Find the maximum salary of a male employee in EMPLOYEE table.
Sql Command:
SELECT Ename, MAX(salary)
FROM EMPLOYEE
WHERE sex=’M’;

Query 4:
Find the total salary of those employees who work in Guwahati city.
Sql Command:
SELECT sum(salary)
FROM EMPLOYEE
WHERE city=’Guwahati’;

Query 5:
Find the number of tuples in the EMPLOYEE relation.
Sql Command:
SELECT count(*)
FROM EMPLOYEE;

42
KV LUMDING VKV:2024_25

 Queries for ALTER & DROP COMMANDS:

Query 1:
To add a new column/attribute with following specification in the EMPLOYEE relation.
Column Name: empstatus, Column data type: varchar(10)

Sql Command:
ALTER TABLE EMPLOYEE ADD empstatus varchar(10) ;

Query 2:
To modify with new specification of an existing column /attribute empstatus with following
specification in the EMPLOYEE relation.
Column Name: empstatus, Column data type: int(5)

Sql Command:
ALTER TABLE EMPLOYEE MODIFY empstatus int(5) ;

Query 3:
To change an existing column /attribute name empstatus by new column /attribute name
estatus with old specification in the EMPLOYEE relation.

Sql Command:
ALTER TABLE EMPLOYEE CHANGE empstatus estatus int(5) ;

Query 4:
To add primary key constraint in an existing column /attribute i.e. estatus in the EMPLOYEE
relation.

Sql Command:
ALTER TABLE EMPLOYEE ADD PRIMARY KEY(estatus) ;

Query 5:
To remove primary key constraint in an existing column /attribute i.e. estatus in the
EMPLOYEE relation.

Sql Command:
ALTER TABLE EMPLOYEE DROP PRIMARY KEY ;

Query 6:
To delete a column/attribute i.e. estatus from the EMPLOYEE relation.

Sql Command:
ALTER TABLE EMPLOYEE DROP COLUMN estatus ;

43
KV LUMDING VKV:2024_25

Q1: Write the SQL commands (i) & (iv), which are based on the following tables,
CUSTOMERS and PURCHASES:

TABLE: CUSTOMERS
CNO CNAME CITIES
C1 SANYAM DELHI
C2 SHRUTI DELHI
C3 MEHER MUMBAI
C4 SAKSHI CHENNAI
C5 RITESH INDORE
C6 RAHUL DELHI
C7 AMEER CHENNAI
C8 MINAKSHI BANGALORE
C9 ANSHUL MUMBAI

TABLE: PURCHASES
SNO QTY PUR_DATE CNO
S1 15 2018-12-25 C2
S2 10 2018-11-10 C1
S3 12 2018-11-10 C4
S4 7 2019-01-12 C7
S5 11 2019-02-12 C2
S6 10 2018-10-12 C6
S7 5 2019-05-09 C8
S8 20 2019-05-09 C3
S9 8 2018-05-09 C9
S10 15 2018-11-12 C5
S11 6 2018-08-04 C7

(i) To display details of all CUSTOMERS whose CITIES are neither Delhi nor Mumbai.
(ii) To display the CNAME and CITIES of all CUSTOMERS in ascending order of their CNAME.
(iii) To display the number of CUSTOMERS along with their respective CITIES in each of the
CITIES.
(iv) To display details of all PURCHASES whose Quantity is more than 15.
(v) To display details of those customers whose name ends with character ‘I’.

SQL Commands:

(i) SELECT * FROM CUSTOMERS


WHERE CITIES NOT IN (“DELHI”, “MUMBAI”) ;
(ii) SELECT CNAME, CITIES FROM CUSTOMERS
ORDER BY CNAME ASC ;
(iii) SELECT CITIES, COUNT(*) FROM CUSTOMERS
GROUP BY CITIES ;
(iv) SELECT * FROM PURCHASES
WHERE QTY > 15 ;
(v) SELECT * FROM CUSTOMERS
WHERE CNAME LIKE “%I”;

44
KV LUMDING VKV:2024_25

Q2: Consider the following tables BOOKS and ISSUED. Write the SQL commands for the
following statements:

TABLE: BOOKS
Book_Id Book_Name Author_Name Publishers Price Type Qty
F0001 The Tears William Hopkins First Publ. 750 Fiction 10
F0002 Thunderbolts Anna Roberts First Publ. 700 Fiction 5
T0001 My first C++ Brian and Brooke EPB 250 Text 10
T0002 C++ Brainworks A.W. Rossaine TDH 325 Text 5
C0001 Fast cook Late Kapoor EPB 350 Cookery 8

TABLE: ISSUED
Book_Id Quantity_Issued
F0001 3
T0001 1
C0001 5

(i) To show Book name, Author name and Price of books of EPB publishers.
(ii) To display the names and price of the books in descending order of their price.
(iii) To increase the price of all books of First Publishers by 50.
(iv) To display the Book_Id, Book_Name and Quantity_Issued for all books which have been
issued.
(v) To insert a new row in the table issued having the following data: “F0002”, 4

SQL Commands:

(i) SELECT Book_Name, Author_Name, Price


FROM BOOKS
WHERE Publishers = “EPB” ;
(ii) SELECT Book_Name, Price
FROM BOOKS
ORDER BY Price DESC ;
(iii) UPDATE BOOKS
SET Price=Price+50
WHERE Publisher = “First Publ.” ;
(iv) SELECT BOOKS.Book_Id, BOOKS.Book_Name, ISSUED.Quantity_Issued
FROM BOOKS, ISSUED
WHERE BOOKS.Book_Id = ISSUED.Book_Id ;
(v) INSERT INTO ISSUED
VALUES(“F0002”, 4);

45
KV LUMDING VKV:2024_25

Q3: Consider the following tables DOCTOR and SALARY. Write the SQL commands for the
following statements:

TABLE: DOCTOR
ID NAME DEPT SEX EXPERIENCE
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15

TABLE: SALARY

ID BASIC ALLOWANCE CONSULTATION


101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300

(i) Display NAME of all doctors who are in “MEDICINE” having more than 10 years’ experience
from the table DOCTOR.
(ii) Display the average salary of all doctors working in “ENT” department using the table
DOCTOR and SALARY. SALARY = BASIC+ALLOWANCE.
(iii) Display the minimum ALLOWANCE of female doctors.
(iv) Display the highest consultation fee amount for all male doctors.

SQL Commands:

(i) SELECT NAME


FROM DOCTOR
WHERE DEPT = “MEDICINE” AND EXPERIENCE > 10 ;
(ii) SELECT AVG(BASIC+ALLOWANCE)
FROM DOCTOR, SALARY
WHERE DOCTOR.ID = SALARY.ID AND DEPT = “ENT” ;
(iii) SELECT MIN(ALLOWANCE)
FROM DOCTOR, SALARY
WHERE DOCTOR.ID = SALARY.ID AND SEX = “F” ;
(iv) SELECT MAX(CONSULTATION)
FROM DOCTOR, SALARY
WHERE DOCTOR.ID = SALARY.ID AND SEX = “M” ;

46
KV LUMDING VKV:2024_25

Q4: Write queries (a) to (d) based on the tables EMPLOYEE and DEPARTMENT given below:
Table: EMPLOYEE

EMPID NAME DOB DEPTID DESIG SALARY


120 Alisha 23-Jan-1978 D001 Manager 75000
123 Nitin 10-Oct-1977 D002 AO 59000
129 Navjot 12-Jul-1971 D003 Supervisor 40000
130 Jimmy 30-Dec-1980 D004 Sales Rep
131 Faiz 06-Apr-1984 D001 Dep Manager 65000

Table: DEPARTMENT

DEPTID DEPTNAME FLOORNO


D001 Personal 4
D002 Admin 10
D003 Production 1
D004 Sales 3

(i) To display the average salary of all employees, department wise.


(ii) To display name and respective department name of each employee whose salary is more
than 50000.
(iii) To display the names of employees whose salary is not known, in alphabetical order.
(iv) To display DEPTID from the table EMPLOYEE without repetition.

SQL Commands:
(i) SELECT AVG(SALARY), DEPTID
FROM EMPLOYEE
GROUP BY DEPTID;
(ii) SELECT NAME, DEPTNAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID AND SALARY>50000;
(iii) SELECT NAME FROM EMPLOYEE
WHERE SALARY IS NULL
ORDER BY NAME;
(iv) SELECT DISTINCT DEPTID
FROM EMPLOYEE;

47
KV LUMDING VKV:2024_25

Q5: Consider the given table Result & write the SQL commands to :

Rollno Name Class DOB Gender City Marks


1 Nanda X 12-10-1998 F Delhi 56
2 Saurabh XI 24-12-1994 M Chennai 45
3 Sanal XII 15-08-2003 M Delhi 66
4 Rekha X 11-09-2004 F Mumbai 81
5 Neha XII 05-06-2006 F Chennai 77

(i) Display the minimum and maximum marks obtained by female students.
(ii) Display different Cities (without repetition) available in table.
(iii) Display the average mark obtained by students of each city.
(iv) Display the class wise total of marks obtained by students.

SQL Commands:
(i) SELECT MIN(MARKS), MAX(MARKS) FROM RESULT WHERE GENDER=’F’;
(ii) SELECT DISTINCT(CITY) FROM RESULT;
(iii) SELECT CITY, AVG(MARKS) FROM RESULT GROUP BY CITY;
(iv) SELECT CLASS, SUM(MARKS) FROM RESULT GROUP BY CLASS;

48

You might also like