Computer Science With Python Practical File
Computer Science With Python Practical File
PRACTICAL FILE
AS PER CBSE GUIDELINES
TEACHER’S SIGNATURE:
.........................................
For eg,score=[200,456,300,100,234,678]
Event-Participants
SQL QUERIES
37 LOANS table queries
38 COMPANY & MODEL table queries
39 STOCK & DEALER table queries
40 PRODUCTS & SUPPLIERS table queries
41 SHOP & ACCESSORIES table queries
IN
PYTHON
PROGRAM 1:
Write a program in python to create four
function calculator.
SNEHA CHAUDHARY Page 8
CODING
result=0
val1=float(input("Enter value 1:"))
val2=float(input("Enter value 2:"))
op=input("Enter any of the operator(+,-,*,/):")
if op=="+":
result=val1+val2
elif op=="-":
if val1>val2:
result=val1-val2
else:
result=val2-val1
elif op=="*":
result=val1*val2
elif op=="/":
if val2==0:
print("Please enter a value other than 0")
else:
result=val1/val2
else:
print("Please enter any one of the operator (+,-,*,/):")
print("The result is:",result)
OUTPUT
SNEHA CHAUDHARY Page 9
PROGRAM 2:
Write a program to generate the table of a
given number using loop.
SNEHA CHAUDHARY Page 10
CODING
num=4
for i in range (1,11):
print (num,'x',i,'=',num*i)
OUTPUT
PROGRAM 3:
Write a program to print cubes of number in
the range 10 to 18.
for i in range(10,18):
print("Cube of number",i,end='')
print("is:",i**3)
OUTPUT
PROGRAM 4:
Write a program to calculate factorial of a
inputted number by using function.
OUTPUT
PROGRAM 5:
Write a program to check whether number is
Armstrong or not.
SNEHA CHAUDHARY Page 13
CODING
num=int(input("Enter 3 digit number:"))
f=num
sum=0
while(f>0):
a=f%10
f=int(f/10)
sum=sum+(a**3)
if(sum==num):
print("It is an Armstrong number:",num)
else:
print("It is not an Armstrong number:",num)
OUTPUT
PROGRAM 6:
Write a program to check whether a number
is Perfect or not.
SNEHA CHAUDHARY Page 14
CODING
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
OUTPUT
PROGRAM 7:
Write a program to generate Fibonacci series
in a tuple.
SNEHA CHAUDHARY Page 15
CODING
nterms=int(input("Fibonacci sequence up to:"))
n1=0
n2=1
count=0
tup=()
if nterms<=0:
print("Please enter a positive integer")
elif nterms==1:
("Fibonacci sequence up to",nterms,":")
print(n1)
else:
print("Fibonacci sequence up to",nterms,":")
while count<nterms:
tup=tup+(n1,)
nth=n1+n2
n1=n2
n2=nth
count+=1
print(tup)
OUTPUT
CODING
str1=input("Enter the string:")
print(str1)
uprcase=0
lwrcase=0
i=0
while i<len(str1):
if str1[i].islower()==True:
lwrcase+=1
if str1[i].isupper()==True:
uprcase+=1
i+=1
print("No. of uppercase letters in the string=",uprcase)
print("No. of lowercase letters in the string=",lwrcase)
OUTPUT
maximum=max(list1)
minimum=min(list1)
mean=sum(list1)/len(list1)
print("Maximum value is =",maximum)
print("Minimum value is =",minimum)
print("Mean value is =",mean)
OUTPUT
for i in l:
print("\nAdmno-",i,":")
z=SCL[i]
print("Name\t","class\t","per\t")
for j in z:
print(j,end="\t")
PROGRAM 11:
SNEHA CHAUDHARY Page 23
Write a program for bubble sort by using
function.
CODING
def main():
l=[64,53,12,78,43,98]
n=len(l)
print("Original List:",l)
for i in range (n-1):
for j in range (n-i-1):
if l [j] > l [j+1]:
l [j], l[j+1]= l[j+1], l[ j]
print("List after sorting is:",l)
OUTPUT
PROGRAM 12:
SNEHA CHAUDHARY Page 24
Write a program for insertion sort by using
function.
CODING
a=[70,54,89,32,54,12,98]
print("Original List:",a)
for i in a:
j=a.index(i)
while j>0:
if a [j-1] > a [j]:
a[j-1], a[j]= a[j], a[ j-1]
else:
break
j=j-1
print("List after sorting is:",a)
OUTPUT
PROGRAM 13:
SNEHA CHAUDHARY Page 25
Write a Python program by using function
that prints the first n rows of Pascal’s
triangle.
CODING
def pascal_triangle():
n = int(input("Enter the number: "))
trow=[1]
y=[0]
for x in range (max(n,0)):
print(trow)
trow=[l+r for l,r in zip (trow+y,y+trow)]
return n>=1
OUTPUT
PROGRAM 14:
SNEHA CHAUDHARY Page 26
Write a program to remove duplicate
characters of a given string.
CODING
s=input("Enter a String:")
i=0
s1=" "
for x in s:
if s.index(x)==i:
s1+=x
i+=1
print (s1)
OUTPUT
PROGRAM 15:
SNEHA CHAUDHARY Page 27
Write a python program to find the highest 3
value in a dictionary.
CODING
# By using nlargest.heapq() function
from heapq import nlargest
my_dict = {'T': 23, 'U': 22, 'P': 21,'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
print(val, " : ", my_dict.get(val))
OUTPUT
PROGRAM 16:
SNEHA CHAUDHARY Page 28
Write a python program to count number of
items in a dictionary value that is list.
CODING
def main():
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using the in operator
count = 0
for x in d:
if isinstance(d[x], list):
count += len(d[x])
print(count)
# Calling Main
if __name__ == '__main__':
main()
OUTPUT
PROGRAM 17:
SNEHA CHAUDHARY Page 29
Write a python program to sort a list
alphabetically in a dictionary.
CODING
dict={'d1': [2, 3, 1], 'd2': [5, 1, 2], 'd3': [3, 2, 4]}
print("\nBefore Sorting:")
for x in dict.items():
print (x)
print("\nAfter Sorting:")
for i,j in dict.items():
sorted_dict={i:sorted(j)}
print (sorted_dict)
OUTPUT
PROGRAM 18:
SNEHA CHAUDHARY Page 30
Write a python program to sort a dictionary
by key.
CODING
a = {'5':'Riya' ,'4':'Priya' ,'6':'Siya' ,'1':'Anisha' ,'3':'Nisha' ,'2':'Isha' }
print(sorted(a.keys()))
print(sorted(a.items()))
OUTPUT
PROGRAM 19:
#main() function
n = int(input("Enter the number: "))
temp = n
res = rev(temp)
if (res == n):
print("Palindrome")
else:
print("Not a Palindrome")
OUTPUT
OUTPUT
PROGRAM 21:
SNEHA CHAUDHARY Page 34
Write a python program by using method to find
and display the prime numbers between 2 to N.
Pass N as argument to the method.
CODING
start = 2
n = int(input("ENTER THE NUMBER UPTOWHICH YOU WANT
PRIME NUMBERS:"))
for val in range(start, n + 1):
if val > 1:
for j in range(2, val//2 + 2):
if (val % j) == 0:
break
else:
if j == val//2 + 1:
print(val)
OUTPUT
PROGRAM 22:
SNEHA CHAUDHARY Page 35
Write a python program by using function
named zeroending(scores) to add all those
values in the list of scores,which are ending
with zero(0) and display the sum.
For eg,score=[200,456,300,100,234,678]
The sum should be displayed as 600.
CODING
def ZeroEnding( SCORES):
s=0
for i in SCORES:
if i%10==0:
s=s+i
print (s)
OUTPUT
PROGRAM 23:
SNEHA CHAUDHARY Page 36
Write a program to calculate the volume and
area of a sphere inside separate modules
and import them in one complete package.
Volume=4/3 π r ∧¿surfacearea=4πr2
3
CODING
#CREATING DIRECTORY
import os
os.mkdir("geometry")
#area module
def sphere_area(r):
return 4*3.14*r**2
#volume module
def sphere_volume(r):
return 4/3*3.14*r**3
OUTPUT
#Creating directory
CODING
file=open("python.txt","r")
lines=file.readlines()
for line in lines:
print(line)
file=open('python.txt','r')
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()
PROGRAM 25:
SNEHA CHAUDHARY Page 42
Read a text file and display the number of
vowels/ consonants/ uppercase/ lowercase
characters in the file.
CODING
file=open("python.txt","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if(ch in['a', 'e', 'i', 'o', 'u','A','E','I','O','U']):
vowels+=1
elif(ch in ['q','w','r','t','y','p','s','d','f','g','h','j','k','l','z','x','c', 'v','b','n','m',
'Q','W','R','T','Y','P','S','D','F','G','H', 'J',
'K','L','Z','X','C','V','B','N','M']):
consonants+=1
file.close()
OUTPUT
PROGRAM 26:
SNEHA CHAUDHARY Page 44
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.
CODING
import pickle
import sys
dict={}
def write_in_file():
file=open("student.dat","ab")
no=int(input("Enter number of students:"))
for i in range (no):
print("Enter student",i+1,"details")
dict["roll"]=int(input("Enter the roll number:"))
dict["name"]=input("Enter the name:")
pickle.dump(dict,file)
file.close()
def display():
file=open("student.dat","rb")
try:
while True:
stud=pickle.load(file)
print(stud)
except EOFError:
SNEHA CHAUDHARY Page 45
pass
file.close()
def search():
file=open("student.dat","rb")
r=int(input("Enter the roll number to search"))
found=0
try:
while True:
data=pickle.load(file)
if data["roll"]==r:
print("Record found successfully...")
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:"))
OUTPUT
CODING
f=open('s1','w+b')
n=int(input('Enter number of students:'))
for i in range(n):
name=input('Enter name of student:')
rollno=input('Enter rollno:')
marks=input('Enter marks:')
bname=bytes(name,encoding='utf-8')
brollno=bytes(rollno,encoding='utf-8')
bmarks=bytes(marks,encoding='utf-8')
f.write(brollno)
f.write(bname)
f.write(bmarks)
f.write(b'\n')
f.seek(0)
data=f.read()
file=open("python.txt","w")
file1=open("py.txt","w")
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("All line that contains a character a has been removed from
python.txt file.")
print("All line that contains a character a has been saved in py.txt
file.")
file.close()
file1.close()
OUTPUT
#Text document
CODING
def f(u):
t=open("story.txt","r")
y=open("ss.txt","a")
c=t.readlines()
line=""
for i in c:
if u in i.split():
line+="Line "+str(c.index(i))+','
k=u+" "*10+line
y.write(k+'\n')
t.close()
y.close()
OUTPUT
#text file
CODING
f1=open("sports.dat","r")
f2=open("Atheletic.dat","w")
s=" "
while s:
s=f1.readline()
s1=s.split('-')
if s1[0].lower()=='Atheletic':
f2.write(s+'\n')
print("Done successfully")
f1.close()
f2.close()
SNEHA CHAUDHARY Page 60
OUTPUT
#sports.dat file in txt form
OUTPUT
OUTPUT
OUTPUT
CODING
Employee=[]
c="y"
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. Display")
choice=int(input("Enter your choice:"))
if(choice==1):
e_id=input("Enter Employee no:")
ename=input("Enter the employee name:")
emp=(e_id,ename)
Employee.append(emp)
elif(choice==2):
if(Employee==[]):
print("Stack Empty")
else:
OUTPUT
OUTPUT
Note:
Comp_ID is the Primary Key.
Table: MODEL
Note:
Model_ID is the Primary Key.
Comp_ID is the Foreign Key referencing
Comp_ID of Company table.
Note:
ItemNo is the Primary Key.
Dcode is the Foreign Key refrencing Dcode of
Dealer table.
Table: Stock
Note:
Dcode is the Primary Key.
Table: SUPPLIERS
Table: ACCESSORIES
CODING
#program to read and research record of employees having
salary is equal to 62000
SNEHA CHAUDHARY Page 91
import mysql.connector as mycon
db1=mycon.connect(host="localhost",user="root",passwor
d="sanchita",database="ABCinfo")
mycursor=db1.cursor()
db1.close()
OUTPUT
CODING
import mysql.connector as mycon
con=mycon.connect(host="localhost",user="root",password
="sanchita",database="ABCinfo")
OUTPUT