[go: up one dir, main page]

0% found this document useful (0 votes)
8 views41 pages

Practical - File - Class - XII - CS - 2024 For Batch 2024 205

Practical_File_Class_XII_CS_2024 for batch 2024 205 including python codes

Uploaded by

msjagtyal
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)
8 views41 pages

Practical - File - Class - XII - CS - 2024 For Batch 2024 205

Practical_File_Class_XII_CS_2024 for batch 2024 205 including python codes

Uploaded by

msjagtyal
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/ 41

Practical File Class XII CS 2024-25

1. Write function to calculate simple interest, function takes three


arguments,p, r, and t. if time is upto 1 year, then rate of interest will be
taken by default 6%, if time is is upto 5 year then rate of interest is 7%
and for time more than five years, the rate is 8%.

def simple_int(p,t,r=6):
return (p*r*t)/100
t=int(input('Enter Time'))
if t<=1:
p=int(input('Enter principal amount'))
print('Rate of interest taken by deafult 6%')
si=simple_int(p,t)
elif t>1 and t<=5:
p=int(input('Enter principal'))
r=7
print('Rate of interest is',r)
si=simple_int(p,t,r)
else:
p=int(input('Enter principal'))
r=8
print('Rate of interest is',r)
si=simple_int(p,t,r)
print('Simple interest is', si)

output : Enter Time 2


principal amount 3000
Rate of interest is 7
Simple interest is : 420

2. Write a function which add 5 to each elements at odd position in list

def sample(x):
for i in range(0,len(x)):
if i%2!=0:
x[i]=x[i]+5
print('List inside function',x)
l=[10,20,30,40,50]
print('Original list',l)
sample(l)
print('List after function use',l)

3. Write a program which calls functions:


1 createdict() to create dictionary at run-time,which stores rno, name
and marks and dob
of students.
2 display() to display records of students who got 300 and above.

def createdict(x):
ch='y'
while(ch!='n'):
r=int(input('Enter rollno'))
n=input('Enter namr')
m=int(input('Enter marks'))
dob=input('Enter dob')
l=[n,m,dob]
x[r]=l
print('Do you want to create more elements')
ch=input('Enter choice y/n')for i in x:
def display():
if x[i][1]>=300:
print('Roll no :',i)
print('Name\t\t dob \t\t marks')
l=x[i]
for j in l:
print(j,end='\t\t')
print()
d={}
createdict(d)
display(d)
4. Write a function which twice the number if it is odd elements of list
and square if it is even element of list.
def twicesquare(x):
l=len(x)
for i in range(0,l):
if x[i]%2==0:
x[i]=x[i]**2
else:
x[i]=2*x[i]

list=[]
n=int(input('Enter how many elements'))
for x in range(1,n+1):
d=int(input('Enter element'))
list.append(d)
print(list)
twicesquare(list)
print('final list is')
print(list)

5. Write function check_prime(), which check whether a number is prime


or not return true other-wise false.
def check_prime(n):
if (n==1):
return False
elif (n==2):
return True
else:
for x in range(2,n):
if(n % x==0):
return False
return True
n=int(input('Enter any number'))
print(check_prime(n))
6. Write a function which counts no of uppercase and lowercase letters in
a string
d={'uppercase':0,'lowercase':0}
def string_count(s):
for c in s:
if c.isupper():
d['uppercase']+=1
elif c.islower():
d['lowercase']+=1
else:
pass
str="Computer Science using Pyhton Programming"
print('Original string: ',str)
string_count(str)
print('Upper case Letters are :',d['uppercase'])
print('lower case letter are :',d['lowercase'])

7. Write function which display Fibonacci series upto n terms.


def fibonacci(n):
a,b=0,1
i=0
while i<=n:
print(a,end=' ')
c=a+b
a,b=b,c
i+=1
n=int(input('Enter how many terms'))
fibonacci(n)
8. Write a program to perform the textfile operations as :
1. Create text file
2. read text file
3. Append text file

def createfile():
f=open("myfile.txt", "w")
f.write("We are in class 12th \n")
f.write("We are studying Python Programming \n")
f.write("Python is a high level language \n")
print("Data written to the file successfully")
f.close()
def readfile():
f= open("myfile.txt","r")
lines=f.readlines()
for x in lines:
print(x)
f.close()
def appendfile():
f=open("myfile.txt", "a")
while True:
s=input('Enter line of text')
f.write(s+'\n')
ch=input('More line of textyes/no')
if ch in ('no','NO','No'):
break

while True:
print("press 1 to create file")
print("press 2 to read file")
print("press 3 to Append file")
print("Enter your choice")
ch=int(input())
if ch==1:
createfile()
elif ch==2:
readfile()
elif ch==3:
appendfile()
else:
break
9. Write a program which counts no of consonent, no of words and no of
words containing digits in a text file.
f= open("c:/users/hp/onedrive/documents/myfile1.txt")
data=f.read()
c=False
cnn=0
for x in data:
c=x not in 'AEIOUaeiou'
if c==True:
cnn=cnn+1
print('No. of consonent',cnn)
list=data.split(' ')
print(list)
w=0
cn=0
c=False
for x in list:
print(x)
w=w+1
c=False
for i in x:
c= i in '0123456789'
if c==True:
break
if c==True:
cn=cn+1
print(data)
print("Number of Words containg digits",cn)
print("Number of words",w)
f.close()

10. Write a program which counts no of lines starting with A in a text file
f=open("C:/Users/hp/Documents/myfile.txt","r")
'''c=0
while True:
l=f.readline()
if l=='':
break
if l[0]=='A':
print(l)
c=c+1
c=1
for l in list:
if l[0]=='A':
print(l,end='')
c=c+1
print('No. of lines starting with A are:',c)
print(list)'''

x=f.readlines()
print(x)
f.close()
11. Program to implement binary file operation such as
1. create binary ("student.dat") which store students records as
rollno, name, class & marks
2. read file and display it content
3. Append file - add record at end of file
4. Modify record- Modify particular record
5. Search record- search particular record
import pickle
def createfile():
f=open('student.dat','wb')
data=[]
ch='Y'
while ch=='Y' or ch=='y':
rno=int(input('Enter rollno'))
name=input('Enter name')
cl=input('Enter class')
marks=int(input('Enter namrks'))
x=[rno,name,cl,marks]
data.append(x)
print('Enter more records Y/N')
ch=input()
pickle.dump(data,f)
print('Data successfully saved')

def readfile():
f=open('student.dat','rb')
try:
while True:
data=pickle.load(f)
for rec in data:
print('Rollno: ',rec[0])
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
print()
except Exception:
f.close()

def searchrec():
r=int(input('Enter roll no of student to be searched'))
f=open('student.dat','rb')
found=False
try:
while True:
data=pickle.load(f)
for rec in data:
if r==rec[0]:
found=True
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
break
except Exception:
f.close()
if found==True:
print('Search successful')
else:
print('Record not exist')

def modifyrec():
f=open('student.dat','rb+')
r=int(input('Enter rollno of student for correction'))
found=False
f.seek(0)
try:
while True:
pos=f.tell()
data=pickle.load(f)
print(pos)
for rec in data:
if r==rec[0]:
found=True
rec[1]=input('Enter Name')
rec[2]=input('Enter Class')
rec[3]=int(input('Enter marks'))
f.seek(pos)
pickle.dump(data,f)
break
except Exception:
f.close()
print(data)

print('File Operation on Student File')


print('1-create file')
print('2- readfile')
print('3= search a record')
print('4- Modifiy record')
ch=int(input('Enter choice'))
if ch==1:
createfile()
elif ch==2:
readfile()
elif ch==3:
searchrec()
elif ch==4:
modifyrec()
else:
print('Exiting')
12. write a program to implement Text file operations such as:
1. create text file
2. read text file and display its content
3. append text in a file
4. count words
5. count lines which starts with 'A'

def createfile():
f=open("myfile.txt","w")
while True:
s=input("Input String")
f.write(s+'\n')
c=input("More string y/n")
if c=='n':
break
f.close()
def readfile():
f=open("myfile.txt","r")
print("\nFile Postion",f.tell())
s=f.readlines()
print(s)
for x in s:
print(x)
f.close()
def countlines():
f=open("myfile.txt","r")
data=f.readlines()
print(data)
c=0
for x in data:
for j in x:
if j[0]=='I':
c=c+1
print('no of lines start with A',c)
f.close()
def appendfile():
f=open("myfile.txt","a")
while True:
s=input("Input String")
f.write(s+'\n')
c=input("More string y/n")
if c=='n':
break
f.close()
def modify():
f=open("myfile.txt","r+")
s=f.readline()
i=1
while s!='':
line=''
s=s.rstrip()
pos=f.tell()
print("\n print position after reading",i,"string ",pos)
L=len(s)
print("Length of",i,"string",L)
line=line+s[0].upper()+s[1:]
print(line)
f.seek(pos-(L+2))
f.write(line+"\n")
print(f.tell())
f.seek(f.tell())
s=f.readline()
i=i+1

f.close()

def countwords():
f=open("myfile.txt","r")
s=f.read()
l=s.split(' ')
print(l)
count=0
for x in l:
if x=='me' or x=='my':
count=count+1
print(count)
while True:
print("\n1- create file")
print("\n2-readfile")
print("\n3- append ")
print("\n4-modify")
print("\n5- count words")
print("\n6 - count lines start with A")
ch=input("\n Input Choice")
if ch=='1':
createfile()
elif ch=='2':
readfile()
elif ch=='3':
appendfile()
elif ch=='4':
modify()
elif ch=='5':
countwords()
elif ch=='6':
countlines()
else:
break;
13. Write a program to perform text file operations as:
1. create file
2. reead file
3. count occurrences of word ‘The’ or ‘the in a file
4. count words which have digits in it.
def createfile():
f=open('myfile.txt','w')
while True:
s=input('Enter Text')
f.write(s+'\n')
print("More text y/n")
c=input()
if c in 'Nn':
break
f.close()

def occurrence():
f=open('myfile.txt','r')
data=f.read()
s=list(data.split(' '))
c=0
for x in s:
if x in ('The','the'):
c=c+1
print('Ocuurence of The is',c)
f.close()
def countwords():
f=open("myfile.txt","r")
s=f.read()
l=s.split()
print(l)
count=0
for x in l:
print (x.isalnum())
if not x.isalpha():
count=count+1

print("no of words",count)

print("1- cratefile")
print("2- occurrence")
print("3-count words")
print("Enter Choice")
ch=input()
if ch=='1':
createfile()
elif ch=='2':
occurrence()
elif ch=='3':
countwords()
else:
print("Wrong choice")

14. Program to implement binary file operation such as :


1. create binary file which stores student record as roll no, name, class and
marks.
2. read binary file and display
3. search for a record in binary file
4. modify a record
import pickle
def createfile():
f=open('student.dat','wb')
data=[]
ch='Y'
while ch=='Y' or ch=='y':
rno=int(input('Enter rollno'))
name=input('Enter name')
cl=input('Enter class')
marks=int(input('Enter namrks'))
x=[rno,name,cl,marks]
data.append(x)
print('Enter more records Y/N')
ch=input()
pickle.dump(data,f)
print('Data successfully saved')

def readfile():
f=open('student.dat','rb')
try:
while True:
data=pickle.load(f)
for rec in data:
print('Rollno: ',rec[0])
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
print()
except Exception:
f.close()

def searchrec():
r=int(input('Enter roll no of student to be searched'))
f=open('student.dat','rb')
found=False
try:
while True:
data=pickle.load(f)
for rec in data:
if r==rec[0]:
found=True
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
break
except Exception:
f.close()
if found==True:
print('Search successful')
else:
print('Record not exist')

def modifyrec():
f=open('student.dat','rb+')
r=int(input('Enter rollno of student for correction'))
found=False
f.seek(0)
try:
while True:
pos=f.tell()
data=pickle.load(f)
print(pos)
for rec in data:
if r==rec[0]:
found=True
rec[1]=input('Enter Name')
rec[2]=input('Enter Class')
rec[3]=int(input('Enter marks'))
f.seek(pos)
pickle.dump(data,f)
break
except Exception:
f.close()
print(data)
while True:
print('File Operation on Student File')
print('1-create file')
print('2- readfile')
print('3= search a record')
print('4- Modifiy record')
ch=int(input('Enter choice'))
if ch==1:
createfile()
elif ch==2:
readfile()
elif ch==3:
searchrec()
elif ch==4:
modifyrec()
else:
print('Exiting')
break
15. Program to connect with database and store records of students.
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='root',dat
abase='school')
mycursor=mydb.cursor()
n=int(input("ENTER HOW MANY REDORDS"))
i=1
rq="insert into student (rno, name, dob) values (%s,%s,%s)"
list=[]
while i <= n:
r=int(input('enter roll no'))
nm=input('enter name')
d=input('enter date of birth')
rtup=(r,nm,d)
list.append(rtup)
i=i+1
print(list)
mycursor.executemany(rq,list)
mydb.commit()
print(mycursor.rowcount,"Record saved")

16. Program to connect with database and search student based on rollno in
table student and display record, if rollno not found display appropriate
message.

import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='root',dat
abase='school')
mycursor=mydb.cursor()
r= int(input('roll no'))
t=(r,)
mycursor.execute("select * from student where rno=%s",t)
for x in mycursor:
print(x)

17. Program to connect with database and update the student record of
entered rollno.
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='root',dat
abase='school')
mycursor=mydb.cursor()
mycursor.execute("update 12a set name='sss' where rno=5")
print("record updated")
mydb.commit()

18. Program to implement the following operations in CSV file “student.csv”


which stores rollno, name, dob and marks of students.
i. Function to create file “student.csv”
ii. Function to read records from file display
iii. Function to add new records in file
import csv
def read_file():
#f=open("C:/Users/hp/Documents/student.csv","r")
with open("C:/Users/hp/Documents/student.csv","r") as f:
data=csv.reader(f)
for row in data:
print(row)
def create_file():
f=open("C:/Users/hp/Documents/student.csv","w")
list=[["rollno","name","dob","marks"]]
while True:
r=int(input('Enter rollno'))
n=input('Enter name')
dob=input('Enter dob')
marks=int(input('Enter marks'))
list.append([r,n,dob,marks])
ch=input('More record y/n')
if ch in ('N','n'):
break
w=csv.writer(f)
#for x in list:
w.writerows(list)
def appendfile():
f=open("C:/Users/hp/Documents/student.csv","a")
list=[]
while True:
r=int(input('Enter rollno'))
n=input('Enter name')
dob=input('Enter dob')
marks=int(input('Enter marks'))
list.append([r,n,dob,marks])
ch=input('More record y/n')
if ch in ('N','n'):
break
w=csv.writer(f)
#for x in list:
w.writerows(list)
while True:
print("1- Create file")
print("2- Read file")
print("3-Append file")
ch=int(input("Enter choice"))
if ch ==1:
create_file()
elif ch==2:
read_file()
elif ch==3:
appendfile()
else:
print("Exit from application")
break
19. Program to implement stack which stores product number and product
name.
def push(stack):
pr_no=input('Enter Product number')
pname=input(‘Enter name of product’)
rec=[pr_no,pname]
stack.append(rec)
print("Element successfully pushed")
def pop(stack):
if stack!=[]:
rec=stack.pop()
print("Popped element is",rec)
else:
print("Stack empty")
def display(stack):
for x in range(len(stack)-1,-1,-1):
print(stack[x])
stack=[]
while True:
print(" \n 1 -push")
print(" \n 2 -pop")
print(" \n 3 -display")
ch=int(input('\n Enter choice'))
if ch==1:
push(stack)
elif ch==2:
pop(stack)
elif ch==3:
display(stack)
else:
print("Wrong choice")
break

SQL queries using one/two tables


Queries Set 1 (Database Fetching records)
[1] Consider the following MOVIE table and write the SQL queries based on it.
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost

The
M001 Kashmir Action 2022/01/26 1245000 1300000
Files

M002 Attack Action 2022/01/28 1120000 1250000

Looop
M003 Thriller 2022/02/01 250000 300000
Lapeta

M004 Badhai Do Drama 2022/02/04 720000 68000

Shabaash Biograp
M005 2022/02/04 1000000 800000
Mithu hy

Romanc
M006 Gehraiyaan 2022/02/11 150000 120000
e

1. Display all information from movie.


2. Display the type of movies.
3. Display movieid, moviename, total_eraning by showing the business done by
the movies. Claculate the business done by movie using the sum of
productioncost and businesscost.
4. Display movieid, moviename and productioncost for all movies with
productioncost greater thatn 150000 and less than 1000000.
5. Display the movie of type action and romance.
6. Display the list of movies which are going to release in February, 2022.

Answers:

[1] select * from movie;

Output:
2. select distinct from a movie;

3. select movieid, moviename, productioncost + businesscost “total earning” from


movie;

4. select movie_id,moviename, productioncost from movie where producst is


>150000 and <1000000;
5. select moviename from movie where type =’action’ or type=’romance’;

6. select moviename from moview where month(releasedate)=2;

Queries Set 2 (Based on Functions)


1. Write a query to display cube of 5.
2. Write a query to display the number 563.854741 rounding off to the next
hnudred.
3. Write a query to display “put” from the word “Computer”.
4. Write a query to display today’s date into DD.MM.YYYY format.
5. Write a query to display ‘DIA’ from the word “MEDIA”.
6. Write a query to display moviename – type from the table movie.
7. Write a query to display first four digits of productioncost.
8. Write a query to display last four digits of businesscost.
9. Write a query to display weekday of release dates.
10. Write a query to display dayname on which movies are going to be released.

Answers:
[1] select pow(5,3);

[2] select round(563.854741,-2);

[3] select mid(“Computer”,4,3);

[4] select concat(day(now()),concat(‘.’,month(now()),concat(‘.’,year(now())))) “Date”;


[5] select right(“Media”,3);

[6] select concat(moviename,concat(‘ – ‘,type)) from movie;

[7] select left(productioncost,4) from movie;


[8] select right(businesscost,4) from movie;

[9] select weekday(releasedate) from movie;


[10] select dayname(releasedate) from movie;

Queries Set 3 (DDL Commands)


Suppose your school management has decided to conduct cricket matches between
students of Class XI and Class XII. Students of each class are asked to join any one
of the four teams – Team Titan, Team Rockers, Team Magnet and Team Hurricane.
During summer vacations, various matches will be conducted between these teams.
Help your sports teacher to do the following:

1. Create a database “Sports”.


2. Create a table “TEAM” with following considerations:
o It should have a column TeamID for storing an integer value between 1
to 9, which refers to unique identification of a team.
o Each TeamID should have its associated name (TeamName), which
should be a string of length not less than 10 characters.
o Using table level constraint, make TeamID as the primary key.
o Show the structure of the table TEAM using a SQL statement.
o As per the preferences of the students four teams were formed as
given below. Insert these four rows in TEAM table:
▪ Row 1: (1, Tehlka)
▪ Row 2: (2, Toofan)
▪ Row 3: (3, Aandhi)
▪ Row 3: (4, Shailab)
o Show the contents of the table TEAM using a DML statement.
3. Now create another table MATCH_DETAILS and insert data as shown below.
Choose appropriate data types and constraints for each attribute.

SecondTea
MatchID MatchDate FirstTeamID SecondTeamID FirstTeamScore
mScore

M1 2021/12/20 1 2 107 93

M2 2021/12/21 3 4 156 158

M3 2021/12/22 1 3 86 81

M4 2021/12/23 2 4 65 67

M5 2021/12/24 1 4 52 88

M6 2021/12/25 2 3 97 68

Answers:

[1] create database sports


[2] Creating table with the given specification

create table team

-> (teamid int(1),

-> teamname varchar(10), primary key(teamid));

Showing the structure of table using SQL statement:

desc team;

Inserting data:

mqsql> insert into team

-> values(1,'Tehlka');
Show the content of table – team:

select * from team;


Creating another table:

create table match_details

-> (matchid varchar(2) primary key,

-> matchdate date,

-> firstteamid int(1) references team(teamid),

-> secondteamid int(1) references team(teamid),

-> firstteamscore int(3),

-> secondteamscore int(3));


Queries set 4 (Based on Two Tables)
1. Display the matchid, teamid, teamscore whoscored more than 70 in first ining
along with team name.
2. Display matchid, teamname and secondteamscore between 100 to 160.
3. Display matchid, teamnames along with matchdates.
4. Display unique team names
5. Display matchid and matchdate played by Anadhi and Shailab.

Answers:

[1] select match_details.matchid, match_details.firstteamid,


team.teamname,match_details.firstteamscore from match_details, team where
match_details.firstteamid=team.teamid and match_details.firstteamscore>70;
[2] select matchid, teamname, secondteamscore from match_details, team where
match_details.secondteamid=team.teamid and match_details.secondteamscore
between 100 and 160;

[3] select matchid,teamname,firstteamid,secondteamid,matchdate from


match_details, team where match_details.firstteamid=team.teamid;

[4] select distinct(teamname) from match_details, team where


match_details.firstteamid=team.teamid;

[5] select matchid,matchdate from match_details, team where


match_details.firstteamid=team.teamid and team.teamname in (‘Aandhi’,’Shailab’);
Queries Set 5 (Group by , Order By)
Consider the following table stock table to answer the queries:

Itemno Item dcode qty unitprice stockdate

S005 Ballpen 102 100 10 2018/04/22

S003 Gel Pen 101 150 15 2018/03/18

S002 Pencil 102 125 5 2018/02/25

S006 Eraser 101 200 3 2018/01/12

S001 Sharpner 103 210 5 2018/06/11

S004 Compass 102 60 35 2018/05/10

S009 A4 Papers 102 160 5 2018/07/17

1. Display all the items in the ascending order of stockdate.


2. Display maximum price of items for each dealer individually as per dcode from
stock.
3. Display all the items in descending orders of itemnames.
4. Display average price of items for each dealer individually as per doce from
stock which avergae price is more than 5.
5. Diisplay the sum of quantity for each dcode.

[1] select * from stock order by stockdate;


[2] select dcode,max(unitprice) from stock group by code;

[3] select * from stock order by item desc;


[4] select dcode,avg(unitprice) from stock group by dcode having avg(unitprice)>5;

[5] select dcode,sum(qty) from stock group by dcode;

You might also like