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

Computer Science Practical File

This document is a practical file for a computer science course, detailing various Python programming tasks and MySQL database operations. It includes user-defined functions for stack operations, file handling, and database connectivity. The document serves as a guide for students to complete their assignments and understand programming concepts.

Uploaded by

Sanyam Bothra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Computer Science Practical File

This document is a practical file for a computer science course, detailing various Python programming tasks and MySQL database operations. It includes user-defined functions for stack operations, file handling, and database connectivity. The document serves as a guide for students to complete their assignments and understand programming concepts.

Uploaded by

Sanyam Bothra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

COMPUTER SCIENCE PRACTICAL FILE

SUBMITTED IN PARTIAL FULFILLMENT OF


THE REQUIREMENTS OF CBSE, NEW
DELHI
SUBJECT CODE: 083

PRUDENCE SCHOOL
Educate • Innovate • Create

CLASS XII
SESSION
2024-2025

Under The Guidance of Submitted By

Name:-Roll No.:
INDEX
Topic Page No.
PYTHON
Q. A list, ‘NList’ contains following record
as list elements: [City, Country, distance
from Delhi]
Each of these records are nested together
to from a nested list. Write the following
user defined functions in Python to perform
the specified operations on the stack
named travel.
i. Push_element(NList) : It takes the nested list as
an argument and pushes a list object containing
name of the city which are not in India and distance
is less than 3500 km from Delhi

ii. Pop_element() : It pops the object from the stack


and display “Stack Empty” when there are no
elements in the stack

Solution:
travel = []

def Push_element(NList):
for i in range(len(NList[0])):
if NList[1][i] != "India" and NList[2][i] < 3500:
travel.append([NList[0][i], NList[1][i]])

def Pop_element():
while len(travel):
print(travel.pop())

else:
print("Stack Empty")

lst = [["Kanyakumari", "Islamabad", "Bishkek", "London",


"Dehradun"],["India", "Pakistan", "Kyrgyzstan", "England",
"India"],[2876, 690.46, 1607.41, 6710, 254]]
for i in lst:
print(i,'\n')

Push_element(lst)
print(travel)

print('\n'*3)
Pop_element()
Q. Python program to implement stack
operations

Solution:
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"
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")
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("Popped item is", item)

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!")
print("\n-----------------------------------------------------------------\
n")
Q. Predict the output of the following code:
def Changevalue(a, b):
for i in range(b):
if a[i]%5 == 0:
a[i] //= 5
if a[i]%3 == 0:
a[i] //= 3

L = [25,8,75,12]
Changevalue(L, 4)
for i in L:
print(i, end = '#')
Q. Predict the output of the following code:

def change(m, n=30):


m=m+n
n=m–n
print(m, '#', n)
return(m)

r = 150
s = 100
r = change(r, s)
print(r, '#', s)
s = change(s)
Q. Predict the output of the following code:

import math as m
import random as rn

print(str(int (m.pow(rn.randint(2,4),2))),end='\n')

print(str(int (m.pow(rn.randint(2,4),2))),end='\n')

print(str(int (m.pow(rn.randint(2,4),2))))
Q. Predict the output of the following code

import random

col=['violet','indigo','blue', 'green','yellow','orange','red']
end=random.randrange(2)+3
begin=random.randrange(end)+1

for i in range(begin,end):
print(col[i],end='&')
Q. Write a program to get the roll numbers,
names and marks of the student of a class (get
from the User) and store these details in a file
called “Marks.txt”

Solution:
cont=int(input('enter no. of entries'))
filOut=open('stud.dat','w')
for i in range(cont):
rol=int(input('Enter roll no.:'))
name=input('name:')
marks=int(input("enter marks"))
rec=str(rol)+","+name+','+str(marks)+'\n'
filOut.write(rec)
filOut.close()
Q. Consider the binary file Stu.dat storing
student details, which you created in earlier
programs. Write a program to update the records
of the file Stu.dat so that those who have scored
more than 81.0, get additional bonus marks of 2.

Solution:
import pickle as p

stud={}
found=False
sk=[1,2]
print('Search keys are:',sk)
fin=open('stud.dat','rb')
try:
print("searching for data")
while True:
stud=p.load(fin)
if stud['roll'] in sk:
print(stud)
found=True

except EOFError:
if found == False:
print("no result found")
else:
print("search succesful")
fin.close()
Q. Write a program to open Stu.dat and search
for records with roll numbers as 12 or 14. If found
display the records.

Solution:
import pickle
stud={}
found=False
fin=open('stud.dat','rb+')
try:
while True:
pos=fin.tell()
stud=pickle.load(fin)
if stud['marks']>81:
stud['marks']+=2
fin.seek(pos)
pickle.dump(stud,fin)
found=True
except EOFError:
if found== False :
print("no matches of record")
else:
print ('records successfully updated.')

fin.close()
print(stud)
Q. Write a python program to open the file
hello.txt used in question no. 6 in read mode to
display contents. What will be the difference if
the file was opened in write mode instead of
append mode?

Solution:
f=open("Hello.txt",'r')
st=' '
while st:
st=f.readline()
print(st)
f.close()
print ('success')
Q.
Write a program to accept string/sentences from
the user till the user enters “END” to. Save the
data in a text file then display only those
sentences which begin with an uppercase
alphabet.

Solution:
f=open("hello.txt","w")
st=" "
while st!="END":
st=input("Enter next line: ")
f.write(st + “\n”)
f.close()

print("\n")
f=open("hello.txt","r")
st=" "
while st:
st = f.readline()
if st:
if st[0].isupper():
print(st)
f.close()
Interface
with MYSQL
import mysql.connector as sql

con = sql.connect(host = 'localhost', user = 'root', password =


'kartik246', database = 'student' )

if con.is_connected():
print(“Connection Successful!”)
else:
print(“Connection was not Successful!”)
import mysql.connector as sql

con = sql.connect(host = 'localhost', user = 'root', password =


'kartik246', database = 'stu')

if con.is_connected():
db = con.cursor()
query = "create table book(accno int(10), name
varchar(230), author char(30), publisher char(30), price
float(20,5), DOP date);"

db.execute(query)
print("Table Created")
import mysql.connector as sql

ado = input("Enter your admission number: ")


na = input("Enter your name: ")
addr = input("Enter your address: ")
fe = input("Enter your fees: ")
dj = input("Enter your date of joining: ")

con = sql.connect(host = 'localhost', user = 'root', password =


'kartik246', database = 'stu')

if con.is_connected():
db = con.cursor()
query = "insert into st(admno, name, adr, fee, doj) values('"
+ ado + "', '" + na + "', '" + addr + "', '" + fe + "', '" + dj + "');"

db.execute(query)
con.commit()
print(db.rowcount, "Record Inserted")
import mysql.connector as sql

admno = input("Enter admission number for which you want


to show the record: ")
addr = input("Enter new value for address: ")

con = sql.connect(host = 'localhost', user = 'root', password =


'kartik246', database = 'stu')
cur = con.cursor()

que = "update st set address ='" + addr + "' where admno = '"
+ admno + "';"

try:
cur.execute(que)
con.commit()
except:
con.rollback()
MYSQL

You might also like