Cs Practical
Cs Practical
Roll no.:-29
thanks to various people who helped me a long way to complete this Practical File.
The harmonies climate in our school provided proper guidance for preparing this file.
Thanks to all my classmates who helped during the development of this file with their
constructive advice.
Name:PRASHANT GUPTA
Class:-12 B
Roll no.:-29
AISSCE PRACTICAL EXAM 2023 COMPUTER
SCIENCE PRACTICAL LIST AS PER CBSE
CURRICULUM PYTHON PROGRAMS
1. Write a program using function to find the factorial of a natural number.
2. Write a program to Input any number from user and check it is Prime no. or not
3. Write a program using function to compute the nth Fibonacci number.
4. Write a program using function to find the sum of all elements of a list.
5. Program to search any word in given string/sentence
6. Read a text file line by line and display each word separated by a #.
7. Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.
8. Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
9. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
10. Remove all the lines that contain the character `a' in a file and write it to
another file.
11. Write a random number generator that generates random numbers between 1 and
6 (simulates a dice).
12. Write a Python program to implement a stack using a list data-structure.
13. Write a Python program to implement a queue using a list data-structure.
14. Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurring word(s).
15. Create a CSV file with EmpNo, Emp name and Salary.Search for a given EmpNo
and display the name and salary,if not found display appropriate message.
16. Write a python program to implement python Mathematical functions.
17. Write a python program to implement python String functions.
18. Write a python program to make user define module and import same in another
module or program.
19. Integrate SQL with Python by importing the MYSQL module to create a table Employee.
20. Integrate SQL with Python by importing the MYSQL module to Insert records in
Employee.
21. Integrate SQL with Python by importing the MYSQL module to search an employee
using Empno and if present in table display the record, if not display appropriate
message.
22. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno, update the record.
23. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno and if present in table delete the record.
Database Management
Create a student table and insert data.
Implement the following SQL commands on the student table:
ALTER table to add new attributes/modify data type/drop attribute.
UPDATE table to modify data.
ORDER BY to display data in ascending / descending order.
DELETE to remove tuple(s).
GROUP BY and find the min, max, sum, count and average.
Program 1: Write a program using function to find the factorial of a natural number.
def factorial(a):
fact = 1
n = num # storing num in n for printing
while num>1:
fact = fact * num
num-=1
return fact
n=int(input("Enter a Number:"))
res=factorial(n)
print("Factorial of ",n,"is",res)
OUTPUT
Enter any number : 8
Factorial of 8 is :
40,320
Program 2: Input any number from user and check it is Prime no. 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 :112
## Number is not Prime ##
>>>
Enter any number :118
## Number is not Prime ##
>>>
Enter any number :113
## Number is Prime ##
>>>
Enter any number :5
## Number is Prime
##
>>>
Enter any number :17
## Number is Prime ##
Program 3: Write a program using function to compute the nth Fibonacci number.
def
fibo(n)
: a=1
b=
1
c=
0
i=
3
if n==1:
print(a
) else:
while i<=n:
c=a+
b
a=b
b=c
i=i+
1
print("nth term of Fibonacci series of ",n,"is",c)
n=int(input("Enter a
Number:")) fibo(n)
OUTPUT
Enter the 'n' term to find in fibonacci :10
10 th term of fibonacci series is : 55
Program 4:Write a program using function to find the sum of all elements of a list.
def sumelements(n):
lst=[ ]
for n in range(num):
numbers=int(input("Enter a number:"))
lst.append(numbers)
sumlist=sum(lst)
return sumlist
list:",sumlist) OUTPUT:
OUTPUT
f=open("Story.txt","a")
s=input("Enter a Story")
f.write(s)
f.close()
f=open("Story.txt","r")
l=f.readline().split()
for w in l:
print(w,end='#')
Output:
Enter a Story: Once upon a time there was magician, who is very Intelligent and
magical too.
Once#upon#a#time#there#was#magician,#who#is#very#Intelligent#and#magical#too.#
Program 7: 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 n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
OUTPUT
Total Vowels in file : 16
Total Consonants in file n : 30
Total Capital letters in file : 2
Total Small letters in file : 44
Total Other than letters : 4
Program 8: 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
import sys
dict={ }
def write_in_file():
file=open("Student.dat","ab") # a-append, b-
binary no=int(input("Enter no of Students"))
for i in range(no):
print("Enter Student ",i+1,"details")
dict["roll"]=int(input("Enter the Roll no:"))
dict["name"]=input("Enter the Name:")
pickle.dump(dict,file) # dump-to write in student file
file.close()
def display():
# read from file and display
file=open("Student.dat","rb") # r-read , b-binary
try:
while True:
stud=pickle.load(file) # reads from file
print(stud)
except EOFError:
pass
file.close()
def search():
file=open("student.dat","rb") # r-read , b-
binary r=int(input("Enter the rollno to
search")) found=0
try:
while True:
data=pickle.load(file) # reads from file
if data["roll"]==r:
print("Record found")
print(data)
found=
1
break
except EOFError:
pass
if found==0:
print("Record not found")
file.close()
# main
program while
True:
print("Menu \n 1-Write in a file \n 2- Display \n 3-Search \n 4-Exit \
n") ch=int(input("Enter your choice"))
if ch==1:
write_in_file(
) if ch==2:
display(
) if ch==3:
search(
) if ch==4:
print("Thank you")
sys.exit()
OUTPUT:
Menu
1-Write in a
file 2- Display
3-
Search
4-Exit
Enter no of Students:3
Enter Student 1 details
Enter the Roll no:1
Enter the Name:sahil
kumar
Enter Student 2 details
Enter the Roll no:2
Enter the Name:sita
Enter Student 2
details
Enter the Roll no:3
Enter the name:ajay
Menu
1-Write in a
file 2- Display
3-
Search
4-Exit
{‘roll’: 3,’name’:’ajay’}
Menu
1-Write in a
file 2- Display
3-
Search
4-Exit
Enter your choice:3
Record found
{'roll': 2, 'name': 'sita '}
Menu
1-Write in a
file 2- Display
3-
Search
4-Exit
def write_in_file():
file=open("Student.dat","ab") # a-append, b-binary
no=int(input("Enter no of Students"))
for i in range(no):
print("Enter Student ",i+1,"details")
dict["roll"]=int(input("Enter the Roll no:"))
dict["name"]=input("Enter the Name:")
dict["Marks"]=input("Enter the Marks:")
pickle.dump(dict,file) # dump-to write in student file
file.close()
def display():
# read from file and display
file=open("Student.dat","rb") # r-read , b-binary
try:
while True:
stud=pickle.load(file) # reads from file
print(stud)
except EOFError:
pass
file.close()
def search():
file=open("student.dat","rb") # r-read , b-
binary r=int(input("Enter the rollno to
search")) found=0
try:
while True:
data=pickle.load(file) # reads from file
if data["roll"]==r:
print("Record found")
print(data)
found=
1
break
except EOFError:
pass
if found==0:
print("Record not found")
file.close()
def update():
file1=open("student.dat","rb") # r-read, b-binary
file2=open("temp.dat","ab") # a-append b-
binary r=int(input("Enter the rollno to update"))
try:
while True:
data=pickle.load(file1) # reads from file
if data["roll"]==r:
print("Enter the new marks for the student:")
data["Marks"]=int(input("Enter the Marks:"))
pickle.dump(data,file2)
else:
pickle.dump(data,file2)
except EOFError:
pass
file1.close(
)
file2.close(
)
os.remove("student.dat")
os.rename("temp.dat","student.dat")
file=open("student.dat","rb") #r-read,b-binary
try:
while True:
stud=pickle.load(file)
print(stud)
except EOFError:
pass
file.close()
# main
program while
True:
print("Menu \n 1-Write in a file \n 2- Display \n 3-Search \n 4-Update \n 5-Exit \
n") ch=int(input("Enter your choice"))
if ch==1:
write_in_file()
if ch==2:
display(
) if ch==3:
search(
) if ch==4:
update(
) if ch==5:
print("Thank you")
sys.exit()
OUTPUT:
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your
choice2
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice1
Enter no of Students2
Enter Student 1
details Enter the Roll
no:1
Enter the Name:seema
Enter the Marks:20
Enter Student 2
details Enter the Roll
no:2
Enter the Name:Divya
Enter the Marks:20
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice2
{'roll': 1, 'name': 'seema', 'Marks': '20'}
{'roll': 2, 'name': 'Divya', 'Marks': '20'}
Menu
1-Write in a
file 2-Display
3-
Search
4-
Update
5-Exit
Enter your choice3
Enter the rollno to update2
Enter the new marks for the student:
Enter the Marks:15
{'roll': 1, 'name': 'seema', 'Marks': '20'}
{'roll': 2, 'name': 'Divya', 'Marks': 15}
Menu
1-Write in a
file 2- Display
3-
Search
4-
Update
5-Exit
Thank you
Q10.Remove all the lines that contain the character `a' in a file and write it to
another file.
f1 = open("first.txt","r" )
lines=f1.readlines()
f1.close()
f1=open("first.txt","w")
f2=open("second.txt","w")
for line in lines:
if 'a' in line:
f2.write(line
)
else:
f1.write(line)
print("All lines removed which contain 'a' from
first.txt") print("All lines added in Second.txt file
which contain a") f1.close()
f2.close(
) OUTPUT:
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
Your Number is :
5
Play More? (Y) :y
Your Number is :
3 Play More? (Y)
:y Your Number is
: 2 Play More?
(Y) :n
Program 12: 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=Non
e 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()
# 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 :20
Cont…
0. EXIT
Enter your choice :1
Enter Item to Push :30
phishingemail=[
"[email protected]",
“[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
OUTPUT
import csv
import math
GCD=math.gcd(num1,num2)
OUTPUT:
# Write a program to accept a string and display the following 1. no. of uppercase
characters # 2. no. of lowercase characters 3. no. of alphabets. 4. no. of digits
str1=input("Enter a string:")
ucount=lcount=dcount=0 #Initialise
for ch in str1: # Select the characters one by one from the
string if ch.isupper(): # if it is uppercase
ucount=ucount+1 # increment
elif ch.islower():
lcount=lcount+1
elif ch.isdigit():
dcount=dcount+1
print(ucount," ",lcount," ",ucount+lcount," ",dcount)
OUTPUT:
Enter a
string:123Python 1 5
6 3
def
sum_odd(n)
: sum=0
for i in range(1,n+1,2):
sum=sum+i
return sum
def sum_even(n):
sum=0
for i in range(2,n+1,2):
sum=sum+i
return sum
print(summodule.sum_series(10))
print(summodule.sum_odd(10))
print(summodule.sum_even(10))
OUTPUT:
35
15
20
18. Integrate SQL with Python by importing the MYSQL module to create a table
Employee. '''Program to create a table Employee with the following Structure:
Empno int primary
key, Ename
varchar(15),
Dept
varchar(15), Sal
int
Display the structure of the table after creation'''
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123")
# to check connection
if
mydb.isconnected()==Tru
e: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
mycursor.execute("Drop Database If Exists Company")
mycursor.execute("CREATE DATABASE COMPANY")
print("Database Created")
mydb.close()
# To Create Table.
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
database="C ompany")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE EMP(EMPNO INTEGER(3), ENAME VARCHAR(20),
DEPT VARCHAR(15), SAL INT)")
print(“Table Created”)
mycursor.execute("DESC
Emp") for row in mycursor:
print(row
)
mydb.close()
OUTPUT:
Connection ok
Database
Created Table
created
('EMPNO', 'int(3)', 'YES', '', None, '')
('ENAME', 'varchar(20)', 'YES', '', None, '')
('DEPT', 'varchar(15)', 'YES', '', None, '')
('SAL', 'int(11)', 'YES', '', None, '')
19.Integrate SQL with Python by importing the MYSQL module to Insert records in
Employee.
'''Program to Insert 5 records into the table Employee with the following
Structure: Empnoint primary key,
Ename varchar(15),
Dept
varchar(15), Sal
int
Display the table content after insertion'''
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="C
ompany")
mycursor=mydb.cursor()
# To insert multiple records
n=int(input("Enter how many records u want to
enter")) for i in range(n):
eno=int(input("Enter the Employee Number:"))
name=input("Enter the Employee Name:")
dname=input("Enter the Department Name:")
sal=int(input("Enter the Employee Salary:"))
query="Insert into Emp values({},'{}','{}',
{})".format(eno,name,dname,sal) mycursor.execute(query)
mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row
) mydb.close()
OUTPUT:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="Com
pany")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to search:"))
mycursor.execute("select * from Emp where
Empno={}".format(eno)) rs=mycursor.fetchall()
for row in rs:
if
row[0]==eno
:
print(row)
else:
print("Record not found")
OUTPUT:
Connection ok
Enter the Employee Number to Search:101
(101, 'Amit Sharma', 'Sales', 80000)
Connection ok
Enter the Employee Number to Search:102
(102, 'Diya Verma', 'Admin', 70000)
21. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno, update the record.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
d atabase="Company")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to search:"))
query="update Emp set sal=80000 where
Empno={}".format(eno) mycursor.execute(query)
mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row)
mydb.close()
print("Row updated Successfully")
OUTPUT:
Connection ok
Enter the Employee Number to search:101
(101, 'Amit Sharma', 'Sales', 80000)
(102, 'Diya Verma', 'Admin', 70000)
Row updated Successfully
22. Integrate SQL with Python by importing the MYSQL module to search a Employee using
Empno and if present in table delete the record.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",
d atabase="Company")
if
mydb.is_connected()==T
rue: print("Connection
ok")
else:
print("Error connecting to mysql database")
mycursor=mydb.cursor()
eno=int(input("Enter the Employee Number to
search:")) query="Delete from Emp where
Empno={}".format(eno) mycursor.execute(query)
mydb.commit()
mycursor.execute("Select * from
Emp") for row in mycursor:
print(row)
mydb.close()
print("Row deleted Successfully")
OUTPUT:
Connection ok
Enter the Employee Number to
search:101 Row deleted Successfully.
Connection ok
Enter the Employee Number to
search:102 Row deleted Successfully.
SQL QUERIES
ii) To display itemno and item name of those items from stock table
whose unit price is more than 10 rupees.
Ans ii) select itemno, item from stock where unitprice>10;
iii) To display details of those items whose dealer code (Dcode) is 102
or quantity in stock (qty) is more than 100 from stock table.
Ans iii) select * from stock where dcode=102 or qty>100;
iii) To display the coach’s name and acodes in ascending order of acode
from table coach.
Ans iii) select name, acode from coach order by acode;