NEW HORIZON SCHOLAR’S
SCHOOL,
KAVESAR, THANE (W)
COMPUTER SCIENCE(083)
PRACTICAL FILE
with
2021 – 2022
Submitted By
NAME: Mili Zankat
CLASS/DIV: 12 E
Roll No.: 08
Exam Seat Number:
Submitted To: Mrs Aarati Mahajan
Index
SN. Program Signature
1 WAP to input a year and check whether the year is leap year or not.
2 WAP to input 3 numbers and print the greatest number using nested it.
WAP to input value of x and n and print the series of x^n along with its sum.x=2 n=5
3
(Output:x^0 x^1…x^n sum)
4 WAP to input a number and check whether its prime number or not.
5 WAP to print Fibonacci series up to n terms, also fine sum of series.
6 WAP to print the given patterns
7 WAP to print a string and the number of vowels present in it
WAP to input a list of numbers and search for a given number using
8
linear search./ binary search
WAP that rotates the elements of a list so that the element at first index moves to the
9 second index, the element at second index moves to the third index and so on and the
element at last index moves to the first index.
Write a program to sort a list using bubble sort and produce sorted list./bubble sort
10
for dictionary keys
Write a menu driven program which will have following functions that takes a
number
11 i) Digisum() – returns sum of digits.
ii) rev() – reverse of a number and also print whether a number is palindrome
or not.
Write function div3and5() that takes 10 elements numeric tuple and return the sum
12
of elements which are divisible by 3 and 5
Write a function that receives two numbers and generates random number from that
13 range. Using this function the main program should be able to print 3 numbers
randomly.
Write a python program to maintain book details like book code, book title and price
14
using stacks data structures? (implement push(), pop() and traverse() functions)
Write a python program to read a file named “[Link]”, count and print the
following:
a) length of the file(total characters in file)
b) total alphabets
15 c) total upper case alphabets
d) total lower case alphabets
e) total digits
f) total spaces
g) total special characters
WAP that copies a text file “[Link]” onto “[Link]” barring the lines starting
16
with a ”@” sign.
A file contains a list of telephone numbers in the following form:
Ashwin 9988776655
17
Shweta 9994445554
WAP to read a file and display its contents in two columns.
WAP that reads characters from the keyboard one by one. All lowercase characters
18 get stored in the file “lower”, all uppercase characters get stored inside a file
“UPPER” and all other characters inside “others”.
Python file/program for interactive binary data file handling (includes
19
insert/search/update/delete operation)
20 Reading and Writing to CSV file.
21 Write A Program To Integrate SQL With Python By Importing The Mysql Module.
22 Take A Sample Of 10 Phishing Emails And Find The Most Common Words.
23 MySQL Queries I
24 MySQL Queries II
Write A Program To Connect Python With MySQL Using Database
25 Connectivity And Perform The Following Operations On Data In Database: Fetch,
Update And Delete The Data.
QUESTION 1
WAP to input a year and check whether the year is leap year or
not.
Code:
Year=int(input("Enter year to be checked:"))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!)
else:
print("The year isn't a leap year!)
Output:
QUESTION 2
WAP to input 3 numbers and print the greatest number using
nested it.
Code:
a=int(input("Enter 1st number : "))
b=int(input("Enter 2nd number : "))
c=int(input("Enter 3rd number : "))
Max=a
if b> Max and b>c:
Max=b
elif b<a and c<a:
Max=a
else:
Max=c
print("is largest number ",Max)
Output:
QUESTION 3
WAP to input value of x and n and print the series of x^n along
with its sum.x=2 n=5
(Output:x^0 x^1…x^n sum)
Code:
x=int(input("Enter value of x: "))
n=int(input("Enter value of n: "))
a=0
for i in range(0,n+1):
print(x**i)
a=a+(x**i)
print("Sum of numbers x^0 till x^n is", a)
Output:
QUESTION 4
WAP to input a number and check whether its prime number or
not.
Code:
number = int(input("Enter The Number: "))\
if number > 1:
for i in range(2,int(number/2)+1):
if (number % i == 0):
print(number, "is not a Prime Number: ")
break
else:
print(number,"is a Prime number")
# If the number is less than 1 it can't be Prime
else:
print(number,"is not a Prime number")
Output:
QUESTION 5
WAP to print Fibonacci series up to n terms, also fine sum of
series.
Code:
first=0
second=1
n=int(input("Fibonacci series:"))
print(first)
print(second)
Sum=0
For a in range(1,n-1):
third=first + second
print(third)
first ,second=second, third
Sum=Sum + third
print("Sum of numbers in Fibonacci series is:",Sum+1)
Output:
QUESTION 6
WAP to print the given patterns
1) Code:
for r in range(1,5): #rows
for c in range(1,r+1): #column
print(c, end="")
print()
Output:
2) Code:
for r in range(1,5): #rows
for c in range(1,r+1): #column
print(r, end="")
print()
Output:
3) Code:
for r in range(1,5):
for c in range(4,r-1,-1):
print(c,end=' ')
print()
Output:
4) Code:
for r in range(1,5):
for c in range(4,r,-1):
print(" ",end='')
print(r)
Output:
5) Code:
for r in range(4,0,-1):
for c in range(4,r,-1):
print(" ",end=" ")
print(r)
Output:
6) Code:
for r inrange(1,5):
for c in range(1,r):
print(" ",end=" ")
print(r)
Output:
7) Code:
for r in range(4,0,-1):
for c in range(1,r):
print(" ",end=" ")
print(r)
Ouput:
8) Code:
for i in range(1,5):
for j in range(1,5):
if(i==j) or (i+j)==5:
print(j,end=" ")
else:
print(end=" ")
print()
Output:
QUESTION 7
WAP to print a string and the number of vowels present in it
Code:
s=input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Output:
QUESTION 8
WAP to input a list of numbers and search for a given number
using linear search/ binary search
Code:
a=eval(input("Enter any list: "))
n=int(input("Enter number to be searched: "))
b=0
for i in range(len(a)):
if n==a[i]:
print("Element",n,"found at index position",i)
b=b+1
if b==0:
print("Element not found in list")
Output:
QUESTION 9
WAP that rotates the elements of a list so that the element at
first index moves to the second index, the element at second
index moves to the third index and so on and the element at last
index moves to the first index.
Code:
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Output:
QUESTION 10
Write a program to sort a list using bubble sort and produce
sorted list./bubble sort for dictionary keys.
Code:
L=eval(input("Enter Any List"))
n=len(L)
for i in range(n):
for j in range(0,n-i-1):
if L[j]>L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
print(L)
Output:
QUESTION 11
Write a menu driven program which will have following
functions that takes a number
i) Digisum() – returns sum of digits.
ii) rev() – reverse of a number and also print whether a number
is palindrome
or not.
Code:
def digisum(n):
rem=0
Sum=0
while n>0:
rem=n%10
Sum=Sum+rem
n=n//10
return Sum
n=int(input("Enter any number: "))
print("Sum of digits is: ",digisum(n))
def reverse(a):
Rev=0
while a>0:
Rem=a%10
Rev=(Rev*10)+Rem
a=a//10
return Rev
a=int(input("Enter number: "))
print("Reverse of the number is : ",reverse(a))
if a==reverse(a):
print("Since reverse of number is equal to the number itself,
Number entered is a palindrome.")
Output:
QUESTION 12
Write function div3and5() that takes 10 elements numeric tuple and
return the sum of elements which are divisible by 3 and 5
Code:
t=[]
for i in range(0,10):
a=int(input("Enter the Number: "))
[Link](a)
t=tuple(t)
print("Entered Tuple is: ",t)
def div3and5(t):
s=0
for i in t:
if i%3==0 and i%5==0:
s=s+i
return s
print("Sum of numbers divisible by both 3 and 5 is: ",div3and5(t))
Output:
QUESTION 13
Write a function that receives two numbers and generates random
number from that range. Using this function the main program should
be able to print 3 numbers randomly.
Code:
from random import randint
def ran(x,y):
return randint(x,y)
x=int(input("Enter number 1:"))
y=int(input("Enter number 2:"))
print("Three random numbers are:",ran(x,y),ran(x,y),ran(x,y))
Output:
QUESTION 14
Write a python program to maintain book details like book code, book
title and price using stacks data structures? (implement push(), pop()
and traverse() functions)
Code:
book=[]
def push():
bcode=input("Enter bcode ")
btitle=input("Enter btitle ")
price=input("Enter price ")
bk=(bcode,btitle,price)
[Link](bk)
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=[Link]()
print("poped element is ")
print("bcode ",bcode," btitle ",btitle," price ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traverse")
print("4. Exit")
ch=int(input("Enter your choice: "))
if ch==1:
push()
elif ch==2:
pop()
print("Remaining elements in Stack are: ")
traverse()
elif ch==3:
traverse()
elif ch==4:
print("End")
break
else:
print("Invalid choice")
Output:
QUESTION 15
Write a python program to read a file named “[Link]”, count and
print the following:
a) length of the file(total characters in file)
b) total alphabets
c) total upper case alphabets
d) total lower case alphabets
e) total digits
f) total spaces
g) total special characters
Code:
a=0 #alphabets
ua=0 #uppercase
la=0 #lowercase
d=0 #digits
sp=0 #spaces
spl=0 #special characters
f=open("[Link]","r")
while True:
c=[Link](1)
if not c:
break
print(c, end="")
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
a=a+1
if (c>='A' and c<='Z'):
ua=ua+1
else:
la=la+1
elif(c>='0' and c<='9'):
d=d+1
elif(c==" "):
sp=sp+1
else:
if(c!="\n"): #Omitting "\n"
spl=spl+1
print("Total alphabets:",a)
print("Total uppercase alphabets:",ua)
print("Total lowercase alphabets:",la)
print("Total Digits:",d)
print("Total spaces:",sp)
print("Total special characters:",spl)
[Link]()
Output:
QUESTION 16
WAP that copies a text file “[Link]” onto “[Link]” barring the
lines starting with a ”@” sign.
Code:
rfp=open("[Link]", "r")
wfp=open("[Link]", "w")
while True:
s1=[Link]()
if len(s1)==0:
break
if s1[0] == "@" :
continue
[Link](s1)
[Link]()
[Link]()
Output:
QUESTION 17
A file contains a list of telephone numbers in the following form:
Ashwin 9988776655
Shweta 9994445554
WAP to read a file and display its contents in two columns.
Code:
print("Ashwin 9988776655")
print("Shweta 9994445554")
file = open("[Link]", "r")
lst = [Link]()
for i in lst :
data = [Link]()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )
[Link]()
Output:
QUESTION 18
WAP that reads characters from the keyboard one by one. All
lowercase characters get stored in the file “lower”, all uppercase
characters get stored inside a file “UPPER” and all other characters
inside “others”.
Code:
a = open("[Link]", "w")
b = open("[Link]", "w")
c = open("[Link]", "w")
while True:
print("Type 1 to start or continue")
print("Type 2 to stop")
ch=int(input("Enter 1 or 2:"))
if ch==1:
d=input("Enter any character from keyboard:")
if(d>="A" and d<="Z"):
[Link](d)
elif(d>="a" and d<="z"):
[Link](d)
else:
[Link](d)
elif ch==2:
print("End")
break
else:
print("Invaild Entry")
break
[Link]()
[Link]()
[Link]()
Output:
QUESTION 19
Python file/program for interactive binary data file handling (includes
insert/search/update/delete operation) .
Code:
import os import pickle
#Accepting data for Dictionary
def insertRec():
rollno = int(input('Enter roll number:')) name = input('Enter
Name:')
marks = int(input('Enter Marks')) #Creating the dictionary
rec = {'Rollno':rollno,'Name':name,'Marks':marks} #Writing the
Dictionary
f = open('[Link]','ab') [Link](rec,f) [Link]()
#Reading the records
def readRec():
f = open('[Link]','rb') while True:
try:
rec = [Link](f)
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks']) except EOFError:
break [Link]()
#Searching a record based on Rollno
def searchRollNo(r):
f = open('[Link]','rb') flag = False
while True: try:
rec = [Link](f) if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks']) flag = True
except EOFError: break
if flag == False:
print('No Records found') [Link]()
#Marks Modification for a RollNo
def updateMarks(r,m):
f = open('[Link]','rb') reclst = []
while True: try:
rec = [Link](f) [Link](rec)
except EOFError: break
[Link]()
for i in range (len(reclst)): if reclst[i]['Rollno']==r:
reclst[i]['Marks'] = m
f = open('[Link]','wb') for x in reclst:
[Link](x,f)
[Link]()
#Deleting a record based on Rollno
def deleteRec(r):
f = open('[Link]','rb') reclst = []
while True: try:
rec = [Link](f) [Link](rec)
except EOFError: break
[Link]()
f = open('[Link]','wb') for x in reclst:
if x['Rollno']==r: continue
[Link](x,f) [Link]()
while 1==1:
print('Type 1 to insert rec.') print('Type 2 to display rec.')
print('Type 3 to Search RollNo.') print('Type 4 to update marks.')
print('Type 5 to delete a Record.') print('Enter your choice 0 to
exit') choice = int(input('Enter you choice:')) if choice==0:
break
if choice == 1: insertRec()
if choice == 2: readRec()
if choice == 3:
r = int(input('Enter a rollno to search:')) searchRollNo(r)
if choice == 4:
r = int(input('Enter a rollno:'))
m = int(input('Enter new Marks:')) updateMarks(r,m)
if choice == 5:
r = int(input('Enter a rollno:')) deleteRec(r)
Output:
➢ Accepting data for dictionary:
➢ Reading the records:
➢ Searching a record based on Rollno:
➢ Marks modification for a RollNo:
➢ Deleting a record based on RollNo:
QUESTION 20
Reading and Writing to CSV file.
Code:
import csv
data = ["Name", "Class", "Div", "Roll no."]
x=[
["Mili", '12th', 'E', '9'],
["Riya", '9th', 'C', '16'],
["Nisha", '10th', 'A', '12'],
["Shreya", '12th', 'B', '17'],
["Divya", '8th', 'D', '7'],
]
y = open("[Link]","w",newline='')
z = [Link](y)
[Link](data)
[Link](x)
[Link]()
#csv file reading code
cFile = open('[Link]','r')
cFileReader = [Link](cFile)
for row in cFileReader:
print(row)
[Link]()
Output: