0% found this document useful (0 votes)
27 views

Shreya Class Xii CS Practical

Uploaded by

dktiwari334
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Shreya Class Xii CS Practical

Uploaded by

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

AMITY INTERNATIONAL

SCHOOL
Session :2022-23

CLASS – XII

Computer
SCIENCE(083)
Practical file
Submitted by:
submitted to:

1
Shreya tiwari Mrs. Cinderalla A
Augustine

Practical File Index


S.n Topic Page
o no
1 UDF to print Fibonacci series 3
2 UDF to find the factorial of a number. 4
3 UDF to find the sum of series. 5
4 UDF to generate the series 6 to 7
1+x1/1!+x2/2!+….xn/n!
5 UDF to check if a given number is palindrome or not. 8 to 9
6 UDF to print a pattern. 10
7 UDF for Binary Search. 11 to12
8 UDF to calculate Cab fare. 13
9 Program to copy the contents the file where the line begins with ‘A’to 14
another file.
10 Program to read and write dictionary to a file. 15
11
PrP Program to accept details of employee as a list and insert 16
into a binary file.
12 Program to read details of employee from the binary file. 17
13 Program to search details of employee from the binary file. 18
14 Program to update details of employee from the binary file. 19
15 Program to read data from CSV file. 20
16 Program to count the no. of records in CSV file 21
17 Program to count the no. of records in CSV file without header 22
18 Program to write emp details to csv file each row at a time. 23
19 Menu Driven program to read and write to CSV file 24
20 Program for Stack 25 to 28
21 Program to connect SQL table with Python to store Student 29
details
22 Menu Driven program to connect SQL table with Python for Item 30 to
details 34
23 Program to connect SQL table with Python to store Employee 35 to
details 38
24 SQL queries 39 to 44

2
1.User defined Functions to print Fibonacci series
nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

3
2. User Defined Function for Factorial Number
def fact(n):

f=1

for i in range(1,n+1):

f=f*i

return(f)

#main

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

r=fact(n)

print("factorial of",n,"=",r)

4
3. User Defined Function for sum of series x0+x1+x2……….xn

def sseries(n,x):

s=0

for i in range(n+1):

s=s+x**i

return(s)

#main

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

x=int(input("Enter the value of x"))

r=sseries(n,x)

5
print("series of",x,"=",r)

4. User Defined program to generate the series 1+x1/1! + x2/2! +


…………xn/n!
def fact(n):

f=1

for i in range(1,n+1):

f=f*i

return(f)

def sseries(n,x):

s=0

for i in range(n+1):

s=s+((x**i)/fact(i))

6
return(s)

#main

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

x=int(input("Enter the value of x"))

r=sseries(n,x)

r1=fact(n)

print("series of",n,"=",r)

print("factorial of",n,"=",r1)

7
5. User Defined by using Function of Palindrome Number
def palindrome(n):

s=0

t=n

while(n>0):

r=n%10

s=(s*10)+r

n=n//10

if(s==t):

return(True)

else:

return(False)

#main

a=int(input("enter the no. to check Palindrome"))

res=palindrome(a)

8
if(res==True):

print(a,"is a Palindrome")

else:

print(a,"is not a palindrome")

9
6. Using UDF to print a pattern
def pattern(n):

for i in range(1,n+1):

for j in range(1,i+1):

print(i*j,end=' ')

print("\n")

#main

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

pattern(n)

10
7. User defined function for Binary Search
def bsearch(a,s,e,x):

if not s<e:

return(-1)

mid=(s+e)//2

if(a[mid]<x):

return bsearch(a,mid+1,e,x)

elif(a[mid]>x):

return bsearch(a,s,mid,x)

else:

return(mid)

11
#main

a=[]

n=int(input("Enter the size of the list"))

a=[0 for i in range(n)]

for i in range(n):

print("enter the value for a[",i,"]")

a[i]=int(input())

a.sort()

x=int(input("Enter the valued to be search"))

index=bsearch(a,0,len(a),x)

if index<0:

print(x,"is not found")

else:

print(x,"is found at index",index)

12
13
8. UDF TO FIND CAB FARE
KM FARE/KM
<=1KM 30
>1 AND <=5KM 25
>5 AND <=15KM 20
>15 AND <=35KM 15
>35KM 10

def bill(n):
b=0
if(n<=1):
b=b+(n*30)
elif(n>1 and n<=5):
b=b+(n*25)
elif(n>5 and n<=15):
b=b+(n*20)
elif(n>15 and n<=35):
b=b+(n*15)
elif(n>35):
b=b+(n*10)
return(b)
#main
n=int(input("enter the kilometers"))
bill=bill(n)
print("total bill=",bill)

14
9. Program to copy the contents where the lines begin by ‘A’
def copy(rfile,wfile):

for1=open(rfile,"r")

fow=open(wfile,"w")

l=[]

l=for1.readlines()

for i in range(len(l)):

if (l[i][0]=='A' or l[i][0]=='a'):

fow.write(l[i]+" ")

for1.close()

fow.close()

rfile=input("enter the file to be read")

wfile=input("enter the file in which data has to be written")

copy(rfile,wfile)

15
10. Program to read and write a dictionary to a file
import pickle
d={}
fo=open(r"xy.dat","wb")
n=int(input("Enter the value of n"))
for i in range(n):
k=input("Enter Customer name as key")
d[k]=input("Enter email id as value")
pickle.dump(d,fo)
fo.close()
fo=open(r"xy.dat","rb")
d1={}
for i in range(n):
d1=pickle.load(fo)
print(d1,"\n")
fo.close()

16
11. Program to accept details of employee as a list and insert into a binary file

import pickle
record=[]
while True:
eno=int(input("Enter employee number"))
name=input("Enter employee name")
dno=int(input("Enter dept number"))
salary=float(input("Enter employee salary"))
b=[eno,name,dno,salary]
record.append(b)
ch=input("Do you want to continue [y/n]:")
if ch.upper()=="N":
break
fo=open("emp.dat","wb")
pickle.dump(record,fo)
fo.close()

17
12. Program to read details of employee from the binary file
import pickle
fo=open("emp.dat","rb")
s=pickle.load(fo)
print(s)
for i in s:
eno=i[0]
name=i[1]
dno=i[2]
salary=i[3]
print(eno,name,dno,salary)
fo.close()

18
13. Program to search details of employee from the binary file

import pickle
fo=open("emp.dat","rb")
s=pickle.load(fo)
eno=int(input("Enter the no. to be searched: "))
found=0
for i in s:
if i[0]==eno:
eno=i[0]
name=i[1]
dno=i[2]
salary=i[3]
print(eno,name,dno,salary)
found=1
break
if found==0:
print("Not Found")
fo.close()

19
14. Program to update details of employee from the binary file
import pickle
fo=open("emp.dat","rb+")
emp_rec=pickle.load(fo)
eno=int(input("Enter the employee no. whose details has to be upd
ate "))
found=0
for r in emp_rec:
if (r[0]==eno):
ch1=input("Do you want to change the dept no.[y/n]")
if (ch1.lower()=='y'):
dn=int(input("Enter the new dept no."))
r[2]=dn
ch2=input("Do u want to change the salary[y/n]")
if (ch2.lower()=='y'):
sal=float(input("Enter the new salary[y/n]"))
r[3]=sal
found=1
break
if (found==1):
fo.seek(0)
pickle.dump(emp_rec,fo)
print("Employee details updated")
else:
print("Employee not found")
fo.close()

20
15. Program to read data from CSV file

import csv
fo=open("test.csv","r")
s=csv.reader(fo)
for row in s:
print(row)
fo.close()

21
16. Program to count the no. of records in CSV file

import csv
fo=open("test.csv","r")
s=csv.reader(fo)
c=0
for row in s:
c+=1
print(c)
fo.close()

22
17. Program to count the no. of records in CSV file without header

23
18. Program to write emp details to csv file each row at a time

24
19. Menu Driven program to read and write to CSV file

25
20. Program for Stack
#stack program

def isEmpty(stk):

if stk==[]:

return True

else:

return False

def Push(stk,item):

stk.append(item)

top=len(stk)-1

def Pop(stk):

if isEmpty(stk):

return"Underflow"

else:

item=stk.pop()

if len(stk)==0:

top=None

else:

top=len(stk)-1

return item

def Peek(stk):

if isEmpty(stk):

return"Underflow"
26
else:

top=len(stk)-1

return stk[top]

def display(stk):

if isEmpty(stk):

print("Stack Empty")

else:

top=len(stk)-1

print(stk[top],"<-top")

for a in range(top -1,-1,-1):

print(stk[a])

#main

stack=[]

top=None

while True:

print("Stack Operations")

print("1.Push")

print("2.Pop")

print("3.Peek")

print("4.Display stack")

print("5.Exit")

27
ch=int(input("enter your choice(1-5):"))

if ch==1:

item=int(input("Enter item:"))

Push(stack,item)

elif ch==2:

item=Pop(stack)

if item=="Underflow":

print("Underflow!stack is empty!")

else:

print

elif ch==3:

item=Peek(stack)

if item=="Underflow":

print("Underflow!stack is empty!")

else:

print("Topmost item is",item)

elif ch==4:

display(stack)

elif ch==5:

break

else:

print("Invalid choice!")

28
29
21. Program to connect SQL table with Python to store Student details.

22. Menu Driven Program to connect SQL table with Python to store
Item details
30
Consider the table “ITEM” having the following fields
Itemcode varchar
Itemname varchar
Price float
i) Create the table ITEM in the mydb database
ii) Create a menu driven program in python to have
a) function for inserting records in the table
b) function for displaying all the records from the table item
c) Function for searching for a particular record on basis of Itemcode.

import sqlite3

def insert_data():

con=sqlite3.connect('db3.db')

cur=con.cursor()

code=int(input("Enter your Item code."))

name= input("Enter the item name")

price=int(input("Enter the item price"))

cur.execute("insert into item (icode,iname,price) values({},'{}',


{})".format(code,name,price))

print("Rows Inserted:", cur.rowcount)

con.commit()

con.close()

def read_all():

con=sqlite3.connect("db3.db")

31
cur=con.cursor()

cur.execute("select * from item;")

d=cur.fetchall()

for i in d:

print(i)

con.close()

def update_data():

con=sqlite3.connect("db3.db")

cur=con.cursor()

code=int(input("Enter the item code whose data is to be updated"))

cur.execute("select * from item where icode={};".format(code))

print("rows=", cur.rowcount)

if (cur.rowcount==-1):

#p=int(input("Enter the roll no to be updated"))

p=int(input("enter the name"))

cur.execute("update stud1 set price='{}' where


icode={};".format(p,code))

con.commit()

con.close()

def search_data():

con=sqlite3.connect("db3.db")

32
cur=con.cursor()

code=int(input("Enter the item code whose data is to be updated"))

cur.execute("select * from item where icode={};".format(code))

d=cur.fetchone()

print("rows=", cur.rowcount)

if (cur.rowcount==1):

print("Searched row=",d)

con.close()

else:

print("Item code not found")

def delete_data():

con=sqlite3.connect("db3.db")

cur=con.cursor()

code=int(input("Enter the item code whose data is to be deleted"))

cur.execute("delete from item where icode={};".format(code))

print("rows=", cur.rowcount)

if (cur.rowcount==1):

print("Deleted row=",code)

con.commit()

con.close()

else:

print("Item code not found")

33
#main

while True:

print("1.Insert data\n 2.Update data\n 3.Delete data \n 4.Read All \n 5.


Search data\n 6.Exit")

ch=int(input("Enter the choice[1-6]"))

if (ch==1):

insert_data()

elif(ch==2):

update_data()

elif (ch==3):

delete_data()

elif (ch==4):

read_all()

elif (ch==5):

search_data()

else:

break

34
35
23. Program to connect SQL table with Python to store Employee details.
import MySQLdb

# Using connect method to connect database

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

using cursor() method for preparing cursor cursor = db1.cursor()

Preparing SQL statement to create EMP table

sql = "CREATE TABLE EMP(empno integer primary key,ename


varchar(25) not null,salary float);"

cursor.execute(sql)

disconnect from server db1.close()

Inserting a record in ‘emp’

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

Prepareing SQL statement to insert one record with the given values sql =
"INSERT INTO EMP VALUES (1,'ANIL KUMAR',86000);"

try:

cursor.execute(sql)

db1.commit()

36
except:

db1.rollback()

db1.close()

Fetching all the records from EMP table having salary more than 70000.
import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sql = "SELECT * FROM EMP WHERE SALARY > 70000;"

try:

cursor.execute(sql)

#using fetchall() function to fetch all records from the table EMP and store
in resultset

resultset = cursor.fetchall()

for row in resultset:

print (row)

37
except:
print ("Error: unable to fetch data")
db1.close()
Updating record(s) of the table using UPDATE
import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )
cursor = db1.cursor()
#Preparing SQL statement to increase salary of all employees whose salary is
less than 80000
sql = "UPDATE EMP SET salary = salary +1000 WHERE salary<80000;"

try:
cursor.execute(sql)
db1.commit()
except:
db1.rollback()
db1.close()

Deleting record(s) from table using DELETE

38
import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sal=int(input("Enter salary whose record to be deleted : ")) #Preparing SQL


statement to delete records as per given condition sql = "DELETE FROM
EMP WHERE salary =sal”

try:

cursor.execute(sql)

print(cursor.rowcount, end=" record(s) deleted ")

db1.commit()

except:

db1.rollback()

db1.close()

Output:

> Enter salary whose record to be deleted: 80000 1

record(s) deleted

>>>

39
24 SQL Queries

40
SOLUTION :

a) Select * from teacher where dept=“History”;

b) Select * from teacher where dept=‘Maths’ and Gender=‘F’;

c) Select name,doj from teacher order by doj asc;

d) Select name,age,salary from teacher where gender=‘M’;

e) Select count(*) from teacher where age>23;

f) Select name,age,sal from teacher where doj>’1997-09-01’;

g) Select count(*) from teacher where salary between 20000 and 30000;

h) Select name,salary,(salary *0.1)+salary as New Sal from teacher;

i) Select name,dept from teacher where name like ‘S%’;

j) Select upper(name) from teacher;

k) Select max(salary) from teacher;

l) Select avg(salary) from teacher where dept=‘Maths’;

m)Select substr(dept,1,3) from teacher;

41
Qno. 2

a. Display name and game of those students whose address is available in


students’ table.
b. To delete a column phone from the table students.
c. Display Name of the students who are studying in class 12 and their
corresponding Coach names.
d. To display count of number of students who play’s volleyball.
e. To display the student name’s, game and coach name who have not
mentioned their phone no.

SOLUTION :
a. Select name,game from students s, sports sp
Where s.admno=sp.admno and address is not null;

b. Alter table students Drop phone;

c. Select name, coachname from students s, sports sp


Where s.admno=sp.admno and class like ‘12_’;

d. Select count(*),game from sports


Where game=’VOLEYBALL’;

e. Select name,game from students s, sports sp


Where s.admno=sp.admno and PHONE is null;

42
Qno. 3

SOLUTION :

i.select * from item where price between 40 and 95;

ii. select customername,city,itemname from item i, customer c where


c.ID=i.ID;

iii. update item


set price=price+50;

iv. select C_ID,customername,city,c.ID,Company from item i, customer c


where i.ID=c.ID;

v. select C_ID,customername,city,c.ID,Company from item i, customer c


where i.ID=c.ID and city="New Delhi";

43
Qno.4

Study the above tables STAFF and SALARY and write SQL command for the
questions (i) to (v).

i. Display NAME of all the staff members who are in SALES having more
than 10 years’ experience from the table staff.

44
ii. Display the minimum ALLOWANCE of female staff.

iii. Display the average Basic Salary of all staff members working in
“Finance” department using the tables staff and salary.

iv. Display the total commission paid to all staff.

v. Display no. of staff in each department.

SOLUTION :

i. Select name,dept,experience from staff


Where dept=’Sales’ and experience>10;

ii. Select min(allowance) from staff st, salary s


Where st.ID=s.ID and gender=’F’;

iii. Select avg(basic) from staff st, salary s


Where st.ID=s.ID and depy= Finance;

iv. Select sum(commission) from salary;

v. Select count(*), dept from staff


Group by dept;

45

You might also like