CS Practical File
CS Practical File
PRACTICAL FILE
-----------------------------------------------------------------------------------
Roll No :
Class : XIIth
CERTIFICATE
This is to certify that Cadet Yash Karansinh Thakor, Roll No: _________
has successfully completed the Practical File in the subject Computer
Science (083) laid down in the regulations of CBSE for the purpose of
Practical Examination in Class XII to be held in St. Xavier’s School,
Silvassa.
Examiner: Principal:
Name: _______________ Name: ______________
Signature: Signature:
ACKNOWLEDGEMENT
Apart from the efforts of me, the success of any project depends largely on the
encouragement and guidelines of many others. I take this opportunity to express my
gratitude to the people who have been instrumental in the successful completion of this
project.
I express a deep sense of gratitude to the almighty God for giving me strength for the
successful completion of the project.
I express my sincere thanks to the academician The Principal of St. Xavier’s School,
Silvassa who has been continuously motivating and extending their helping hand to us and
for constant encouragement and the guidance provided during this project.
The guidance and support received from all the members who contributed and who
are contributing to this project, was vital for the success of the project. I am grateful for
their constant support and help.
INDEX
12. Read a text file line by line and display each word
separated by #.
14. Remove all the lines that contain the character a’ in a file
and write it to another file.
19. Take a sample of ten phishing e-mails (or any text file)
and find most commonly occurring words.
Code:
Output:
Program 2:
Write a program to find whether an inputted number is perfect or not.
Code:
Output:
Program 3:
Write a Program to check if the entered number is Armstrong or not.
Code:
Output:
Program 4:
Write a Program to find the factorial of the entered number.
Code:
Output:
Program 5:
Write a Program to enter the number of terms and to print the Fibonacci Series.
Code:
Output:
Program 6:
Write a Program to enter the string and to check if it’s palindrome or not using a loop.
Code:
def palindrome(str):
for j in range(0, int (len(str)/2)):
if str[j] != str[len(str)-j-1]:
return False
return True
s = input("Enter a string:")
answer = palindrome(s)
if(answer):
print("Yes, it is a palindrome.")
else:
print("No, it is not a palindrome.")
Output:
Program 7:
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)
Code:
import random
min = 1
max = 6
roll_dice_again = "y"
while roll_dice_again == "y" or roll_dice_again == "Y":
print("Rolling the dice...")
value = random.randint (min, max)
print("You got...", value)
roll_dice_again = input("Roll the dice again? (y/n): ")
Output:
Program 8:
Write a program that generates a series using a function while takes first and last values of the series
and then generates four terms that are equidistant e.g., if two number passed are 1 and 7 then
function returns 1-3-5-7.
Code:
def series(a,b):
d = int((b-a)/3)
print("Series is =",a,a+d,a+2*d,b)
Output:
Program 9:
Write a Python program using a function to print factorial number series from n to m numbers.
Code:
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1);
num = int(input("Enter a number: "))
print("Factorial of", num, "is", factorial(num))
Output:
Program 10:
Write a Python program to demonstrate the concept of variable length argument to calculate the
product and power of the first 10 numbers.
Code:
Output:
Program 11:
Write a Python program to accept the username “Admin” as the default argument and password 123
entered by the user to allow login into the system.
Code:
Output:
Program 12:
Read a text file line by line and display each word separated by #.
Code:
f = open("file1.txt")
for x in f:
words =x.split()
for w in words:
print(w + '#', end= "")
print()
f.close()
TXT File:
Output:
Program 13:
Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the
file.
Code:
f = open("file2.txt")
v = 0
c = 0
u = 0
l = 0
o = 0
d = f.read()
vowels = ['a','e', 'i', 'o', 'u']
for ch in d:
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:", c)
print("Total capital letters in file:", u)
print("Total small letters in file:", l)
print("Total other than letters in file:", o)
f.close()
TXT File:
Output:
Program 14:
Remove all the lines that contain the character ‘a’ in a file and write it to another file.
Code:
def Remove():
oldf = open("oldfile.txt","r")
newf = open("newfile.txt", "w")
L = []
lines = oldf.readlines ()
for line in lines:
if 'a' in line:
newf.write(line)
else:
L.append(line)
oldf = open("oldfile.txt", "w")
oldf.writelines(L)
oldf.close()
newf.close()
print("File copied successfully.")
Remove()
Code:
import pickle
def write():
D={}
f = open("studentdetails.dat", "wb")
while True:
r = int(input("Enter Roll no:"))
n = input("Enter Name:")
D['Roll No'] = r
D['Name'] = n
pickle.dump(D, f)
ch = input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()
def search():
found = 0
rollno = int(input("Enter Roll No whose name you want to display:"))
f = open("studentdetails.dat","rb")
try:
while True:
rec = pickle.load(f)
if rec ['Roll No'] == rollno:
print(rec["Name"])
found = 1
break
except EOFError:
f.close()
if found == 0:
print("Sorry not found...")
print("Sorry not found...")
f.close()
write()
search ()
Output:
Program 16:
Create a binary file with roll number, name and marks. Input a roll number and update the marks.
Code:
import pickle
def Write():
f=open('studentdetails.dat', 'wb')
while True:
r=int(input("Enter Roll Number: "))
n=input("Enter Name: ")
m = int(input("Enter Marks: "))
record=[r,n,m]
pickle.dump(record, f)
ch=input("Do you want to enter more records (Y/N): ")
if ch in 'Nn':
break
f.close()
def Read():
f=open('studentdetails.dat','rb')
try:
while True:
rec=pickle.load(f)
print (rec)
except EOFError:
f.close()
def Update():
f=open('studentdetails.dat','rb+')
rollno=int(input("Enter Roll no whose marks you want to update: "))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Updated Marks: "))
rec [2]=um
f.seek(pos)
pickle.dump(rec, f)
except EOFError:
f.close()
Write ()
Read()
Update()
Read()
Output:
Program 17
Create a CSV file by entering user-id and password, read and search the password for given user-id.
def read():
f = open("details.csv", "r")
ro = csv.reader (f)
for i in ro:
print(i)
f.close()
write()
read()
Output:
Output in Excel:
PART 2 – TO SEARCH THE USER
Code:
def read():
f = open("details.csv","r")
ro = csv.reader (f)
for i in ro:
print(i)
f.close()
def search():
f = open("details.csv","r")
u = input("Enter UserId to search:")
ro = csv.reader(f)
for i in ro:
if i[0] == u:
print(i[1])
f.close()
write()
read()
search ()
Output:
Output in Excel:
PART 3 – TO CHECK IF USER FOUND OR NOT
Code:
def read():
f = open("details.csv","r")
ro = csv.reader(f)
for i in ro:
print(i)
f.close()
def search():
f = open("details.csv","r")
Found = 0
u = input("Enter UserId to search: ")
ro = csv.reader(f)
next(ro)
for i in ro:
if i[0] == u:
print(i[1])
Found = 1
if Found == 0:
print("Sorry, no record found.")
f.close()
read()
search()
Code:
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def add(stk,item):
stk.append(item)
top = len(stk)-1
stack = []
top = None
while True:
print("STACK OPERATION:")
print("1.Add student")
print("2.Display stack")
print("3.Remove student")
print("4.Exit")
ch=int(input("Enter your choice (1-4): "))
if ch==1:
rno=int(input("Enter Roll no to be inserted: "))
sname=(input("Enter Student name to be inserted: "))
item=[rno, sname]
add (stack, item)
input()
elif ch==2:
display (stack)
input()
elif ch==3:
remove (stack)
input()
elif ch==4:
break
else:
print("Invalid choice")
input()
Code:
phishingemail = ["hellouser@snapdeal.com",
"luckywinner@lottery.com",
"jackpot@flipkart.com",
"claimtheprize@snapdeal.com",
"youwon@money.com",
"spinthewheel@mymoney.com"
"hellouser@lottery.com",
"scratchthegift@amazon.com"
"dealwinner@snapdeal.com",
"luckyjackpot@myntra.com"]
d={}
for x in phishingemail:
i=x.split('@')
for a in i:
if a not in d:
d[a]=1
else:
d[a]+=1
maxw = max(d,key=d.get)
print("Most Common Occuring Word is:", maxw)
Output:
Program 20:
Write a Python program to accept a list as a function parameter and raise the Index Error exception.
Code:
Output:
Program 21:
Write a program to accept the number of days and display appropriate weeks in an integer. Display an
appropriate error message through multiple exception handling including the finally clause.
Code:
print("Handling exception using try, except, else & finally.")
try:
day= int(input("Enter a number 1-7: "))
if (day==1):
print(day," is Sunday")
elif (day==2):
print (day," is Monday")
elif (day==3):
print(day," is Tuesday")
elif (day==4):
print(day," is Wednesday")
elif (day==5):
print(day," is Thursday")
elif (day==6):
print(day," is Friday")
elif (day==7):
print(day," is Saturday")
else:
print("Wrong input.")
except:
print("Only numbers are to be entered.")
finally:
print("End of program.")
Output:
&
Program 22:
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.
• GROUP BY and find the min, max, sum, count and average.
Code:
GROUP BY max:
GROUP BY average:
GROUP BY sum:
GROUP BY count:
Program 23:
Integrate SQL with Python by importing the MySQL module.
if mydb.is_connected():
print("Connection is established.")
Output:
Program 24:
Write a program to connect Python with MySQL using database connectivity and perform the following
operations on data in database: Fetch, Update and delete the data
Code in MySQL:
Code:
for i in cursor:
print(i)
Output:
> Table already existing in MySQL:
Output:
Code for Python to do fetchmany(size) function:
import mysql.connector as msc
mydb = msc.connect(host = 'localhost', password = 'yash2007',
user = 'root', database = 'cs_pr_file')
cursor = mydb.cursor()
cursor.execute('select * from stud_marks')
records = cursor.fetchmany(5)
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)
for i in records:
print(i)
Output:
Code for Python to do fetchall() function:
import mysql.connector as msc
mydb = msc.connect(host = 'localhost', password = 'yash2007',
user = 'root', database = 'cs_pr_file')
cursor = mydb.cursor()
cursor.execute('select * from stud_marks')
records = cursor.fetchall()
no_rec = cursor.rowcount
print("Total no. of records found in DB are:", no_rec)
for i in records:
print(i)
Output: