Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

WOODBRIDGE SCHOOL, BHIMTAL

Practical File On
PYTHON PROGRAMMING

Submitted to:
Submittedby:
Miss Pragati Bisht Mohit Rawat
PGT(Computer Science) Class-
XII(Science)
Acknowledgemen
t
I would like to express my special thanks of gratitude to my
Computer Science Teacher , Ms. Pragati Bisht as well as
our Principal , Mrs. Anita Kerr who gave me the golden
opportunity to do this wonderful project of Computer
Science, which also helped me in doing a lot of Research
and I came to know about so many new things I am really
thankful to them.
Secondly, I would also like to thank my parents and friends
who helped me a lot in finalizing this project within the
limited time frame.

_________________ _________________
Principal’s Signature Teacher’s Signature
CERTIFICATE

This is to certify that Mohit Rawat, a student of classXII of


WOODBRIDGE School, has been successfully completed his
Computer Science practical report file under the guidance of
Miss Pragati Bisht.

_________________ _________________
Principal’s Signature Teacher’s Signature
CONTENTS
S.No. Program Teacher’s sign
1. Program that reads a line and prints its statistics
Program to create a dictionary containing name
2.
of competition winners
3. Program that sorts a list using bubble sort
4. Program that sorts a list using insertion sort
Program to calculate simple interest using a
5. function interest() that receives principal amount,
time and Rate of Interest
Program that receives two numbers and returns
6.
results of all arithmetic operators
Program which displays the size of a file after
7.
removing EOL characters, white spaces
Program to get student details and store them in
8.
a text file.
Program to read a text file line by line and display
9.
each word separated by #
Program to read a text file and display count of
10.
vowels and consonants in it
Program to get student data from user and write
11.
onto a binary file
12. Program to open a file and search for its records
Program to read file created earlier and display
13.
records having marks>81
Program to modify a record in an already existing
14.
file
Program to store student data (obtained from the
15
user)
Program to create a CSV file and writing student
16.
data into it
Program to create a CSV file by suppressing EOL
17.
translation.
Program that uses recursive function to print a
18.
string backwards
Program that uses recursion in calculation of
19.
power
Program that uses recursive function to print
20.
Fibonacci series upto nth term
Program which uses recursive function to
21.
implement binary search algorithm
Program:1: Program that reads a line and prints its statistics like:
Number of upper case letters:
Number of lower case letters:
Number of alphabets:
Number of digits:

line=input("Enter a line:")

lowercount=uppercount=0

digitcount=alphacount=0

for a in line:

if a.islower():

lowercount+=1

elif a.isupper():

uppercount+=1

elif a.isdigit():

digitcount+=1

if a.isalpha():

alphacount+=1

print("Number of uppercase letters:",uppercount)

print("Number of lowercase letters:",lowercount)

print("Number of digits:",digitcount)

print("Number of alphabets :",alphacount)

Output:
Program: 2: Write a program to create a dictionary containing names of
competition winner
students as keys and number of their wins as values.

n=int(input("How many students?"))

CompWinners={}

for a in range(n):

key=input("Name of the student:")

value=int(input("Number of competitions won:"))

CompWinners[key]=value

print("The dictionary now is:")

print(CompWinners)

Output :
Program:3: Program to sort a list using Bubble sort.

alist=[12,3,421,1,312,55,31,13,43]

print("Original list is:",alist)

n=len(alist)

for i in range (n):

for j in range(0,n-i-1):

if alist[j]>alist[j+1]:

alist[j],alist[j]=alist[j+1],alist[j]

print("List after sorting is:",alist)

Output:
Program:4: Program to sort a sequence using insertion sort.

alist=[12,23,43,5,2,456,774,11,131,22,4,55,5,1]

print("Original list is",alist)

for i in range(1,len(alist)):

key=alist[i]

j=i-1

while j>=0 and key<alist[j]:

alist[j+1]=alist[j]

j=j-1

else:

alist[j+1]=key

print("List after sorting is:",alist)

Output:
Program:5: Program to calculate simple interest using a function interest( ) that
can receive principal amount, time and rate and returns calculated
simple interest. Do specify default values for rate and time as 10%
and 2 years respectively.

def interest(principal,time=2,rate=0.10):

return principal*rate*time

prin=float(input("Enter principal amount:"))

print("Simple interest with default ROI and time values is:")

si1=interest(prin)

print("Rs.",si1)

roi=float(input("Enter rate of interest(ROI):"))

time=int(input("Enter time in years:"))

print("Simple interest with your provided ROI and time values is:")

si2=interest(prin,time,roi/100)

print("Rs.",si2)

Output:

Program:6: Program that receives two numbers in a function and returns the
results of all arithmetic operations (+, -, *, /, %) on these numbers.

def arCalc(x,y):

return x+y,x-y,x*y,x/y,x%y

num1=int(input("Enter number 1:"))

num2=int(input("Enter number 2:"))

add, sub, mult, div, mod=arCalc(num1,num2)

print("Addition of given number:",add)

print("Subtraction of given number:",sub)

print("Multiplication of given number:",mult)

print("Division of given numbers:",div)

print("Modulo of given numbers:",mod)

Output:

Program:7: Displaying the size of a file after removing EOL characters, leading
and trailing white spaces and blank lines.
myfile=open(r'F:\python.txt',"r")

str1=" "

size=0

tsize=0

while str1:

str1=myfile.readline()

tsize=tsize+len(str1)

size=size+len(str1.strip())

print("Size of file after removing all EOL characters & blank lines:",size)

print("The total size of the file:",tsize)

myfile.close()

Output:

Program:8: Write a program to get roll numbers, names and marks of the
students of a class (get from user) and store these details in a file
called “Marks.txt”.

count=int(input("How many students are there in the class?"))

fileout=open("Marks.txt","w")

for i in range(count):

print("Enter details for student",(i+1),"below:")

rollno=int(input("Roll no.:"))

name=input("Name:")

marks=float(input("Marks:"))

rec=str(rollno)+","+name+","+str(marks)+'\n'

fileout.write(rec)

fileout.close()

Output:

Program:9: Write a program to read a text file line by line and display each
word separated by a ‘#’.
myfile=open(r'F:\Answer.txt',"r")

line=" "

while line:

line=myfile.readline()

for word in line.split():

print(word,end='#')

print()

myfile.close()

Output:

Program:10: Write a program to read a text file and display the count of vowels
and consonants in the file.
myfile=open("F:/Answer.txt","r")

ch=" "

vcount=0

ccount=0

while ch:

ch=myfile.read(1)

if ch in['a','A','e','E','i','I','o','O','u','U']:

vcount=vcount+1

else:

ccount=ccount+1

print("Vowels in the file:",vcount)

print("Consonants in the file:",ccount)

myfile.close()

Output:

Program:11: Write a program to get student data (roll no., name and marks )
from user and write onto a binary file. The program should be able
to get data from the user and write onto the binary file as long as
the user wants.

import pickle

stu={}

stufile=open('Stu.dat','wb')

ans='y'

while ans=='y':

rno=int(input("Enter Roll Number:"))

name=input("Enter name:")

marks=float(input("Enter marks:"))

stu['Rollno']=rno

stu['Name']=name

stu['Marks']=marks

pickle.dump(stu,stufile)

ans=input("Want to enter more records?(y/n).........")

stufile.close()

Output:

Program:12: Write a program to open file Stu.dat and search for records with
roll numbers 12 or 13. If found display the records.

import pickle
stu={}

found=False

fin=open('Stu.dat','rb')

searchkeys=[12,13]

try:

print("Searching in file Stu.dat.....")

while True:

stu=pickle.load(fin)

if stu['Rollno'] in searchkeys:

print(stu)

found=True

except EOFError:

if found==False:

print("No such record found in the file")

else:

print("Search successful.")

fin.close()

Output:

Program:13: Read the file Stu.dat created in earlier programs and display
records having marks >81.

import pickle
stu={}

found=False

print("Searching in file Stu.dat........")

with open('Stu.dat','rb')as fin:

stu=pickle.load(fin)

if stu['Marks']>81:

print(stu)

found=True

if found==False:

print("No records with Marks>81")

else:

print("Search Successful")

Output:

Program:14: Write a program to modify the name of rollno as Rohit in file


Stu.dat (Created in earlier programs).

import pickle
stu={}

found=False

fin=open('Stu.dat','rb+')

try:

while True:

rpos=fin.tell()

stu=pickle.load(fin)

if stu['Rollno']==12:

stu['Name']='Rohit'

fin.seek(rpos)

pickle.dump(stu,fin)

found=True

except EOFError:

if found==False:

print("Sorry, no matching record found.")

else:

print("Record successfully updated.")

fin.close()

Output:

Program:15: Write a program to create a CSV file to store student data (Rollno.,
Name, Marks). Obtain data from user and write 5 recors into the
file.
import csv

fh=open("Student.csv","w")

stuwriter=csv.writer(fh)

stuwriter.writerow(['Rollno','Name','Marks'])

for i in range(5):

print("Student record",(i+1))

rollno=int(input("Enter rollno:"))

name=input("Enter Name:")

marks=float(input("Enter Marks:"))

sturec=[rollno,name,marks]

stuwriter.writerow(sturec)

fh.close()

Output:

Program:16: The data of four rounds of a programming competition is given as:


['Name','Points','Rank'],

['Shradha','4500','23'],

['Nishchay','4800','15'],

['Ali','5100','11'],
['Sashwat','5200','10']

Write a program to create a CSV file (compresult.csv) and write


the above data into it.

import csv

fh=open("compresult.csv","w")

cwriter=csv.writer(fh)

compdata=[

['Name','Points','Rank'],

['Shradha','4500','23'],

['Nishchay','4800','15'],

['Ali','5100','11'],

['Sashwat','5200','10']]

cwriter.writerows(compdata)

fh.close()

Output:

Program:17: Write a program to create a CSV file by suppressing the EOL


translation.

import csv
fh=open("Employee.csv","w",newline="")

ewriter=csv.writer(fh)

empdata=[

['Empno','Name','Designation','Salary'],

[1001,'Trupti','Manager',56000],

[1002,'Raziya','Manager',55900],

[1003,'Harshit','Analyst',35000],

[1004,'Sanya','Clerk',25000],

[1005,'Sofiya','PR Officer',31000]]

ewriter.writerows(empdata)

print("File successfully created")

fh.close()

Output:

Program:18: Write a recursive function to print a string backward.

def bp(sg,n):

if n>0:

k=len(sg)-n
bp(sg,n-1)

print(sg[k],end='')

elif n==0:

return

s=input("Enter a string:")

bp(s,len(s))

Output:

Program:19: Program to show the use of recursion in calculation of power e.g.,


ab.

def power(a,b):

if b==0:
return 1

else:

return a*power(a,b-1)

print("Enter only positive numbers below")

num=int(input("Enter base number:"))

p=int(input("Raise to the power of:"))

result=power(num,p)

print(num,"raised to the power of",p,"is",result)

Output:

Program:20: Program using a recursive function to print Fibonacci series upto


nth term.

def fib(n):

if n==1:
return 0

elif n==2:

return 1

else:

return fib(n-1)+fib(n-2)

n=int(input("Enter last term required:"))

for i in range (1,n+1):

print(fib(i),end=',')

print(".......")

Output:

You might also like