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

AIR FORCE BAL BHARTI SCHOOL

COMPUTER SCIENCE
PRACTICAL FILE
NAME : HRISHANT TRIPATHI
CLASS : 12-C
ROLL NO. : 23
S.N ACTIVITY
O
1 RANDOM NUMBERS
2 KEYWORD ARGUMENTS
3 ODD-EVEN
4 USING TEXT FILES
5 USING BINARY FILES
6 CALCULATIONS
7 CSV FILES
8 FIBONACCI SERIES
9 FACTORIAL OF A NUMBER
10 COUNTING NUMBER OF CONSONANTS
11 COUNTING NUMBER OF VOWELS

12 COUNTING THE AND THESE


13 STACK FILES
14 SQL PYTHON CONNECTOR
15 REVERSING A STRING
INPUT OUTPUT
Q) Write a program for generating 5 random numbers 3
and their list. 9
9
import random 1
l=[] 8
for i in range (5): [3, 9, 9, 1, 8]
x=random.random()
y=int(x*10)
l.append(y)
print(y)
print(l)
Q) Write a program to generate 5 random number 20
between 10 and 20. 10
11
import random 15
l=[] 20
for i in range (5):
x=int(random.random()*11)+10
print(x)
Q) Write a program to generate random numbers 31
between 20 and 50. 42
43
import random 46
for i in range(5): 32
x=random.randint(20,50)
print(x)
Q) Write a python program to demonstrate Keyword Geeks Practice
Arguments. Geeks Practice

def student(firstname,lastname):
print(firstname,lastname)
# Keyword arguments
student(firstname ='Geeks',lastname ='Practice')
student(lastname ='Practice',firstname ='Geeks')
Q) Write a python program to check whether a given Enter your number:31
number x is even or odd. Odd
Enter your number:22
def evenOdd( x ): Even
if (x % 2 == 0):
print("even")
else:
print("odd")
x=int(input("Enter your number:",))
evenOdd(x)
Q) Write a program to use write function on text files. My first line of code
to enter data into a text file
f=open("one.txt","w") we will do binary files later
f.write("My first line of code \n")
f.write("to enter data into a text file \n")
f.write("we will do binary files later \n")
print("File Created Successfully!!!")
f.close()
Q) Write a program to perform simple mathematics enter no1 42
calculations. enter no2 39
Result 7
def add(x,y): Result 81
r=x+y 1638
print("Result ",r) 1.0769230769230769
return(r) Result= 3
def sub(x,y):
r=x-y
return(r)
def pro(x,y):
r=x*y
print(r)
return(x*y)
def div(x,y):
if y==0:
print("Zero Division ERROR!!")
else:
r=x/y
print(r)
return(x/y)
#End of Module
no1=int(input("enter no1 "))
no2=int(input("enter no2 "))
add(4,3)
add(no1,no2)
pro(no1,no2)
div(no1,no2)
#print("Result of addition ",r)
Res=sub(no1,no2)
print ("Result= ",Res)

Q) Write a python program to us writelines in text file. enter list values11 Hrishant Tripathi 96 A+
f=open("two.txt","w") File Created Successfully!!!
l=[]
f.writelines(["10\n","Aditya Pratp\n","98","A+"]) 10
l=input("enter list values") Aditya Pratp
f.writelines(l) 98A+11 Hrishant Tripathi 96 A+
print("File Created Successfully!!!")
f.close()
Q) Write a python program to use an existing file. enter list valuesHRISHANT1 20
do you want to continue?y
f=open("two.txt","w") enter list valuesHRISHANT2 21
l=[] do you want to continue?y
ch='y' enter list valuesHRISHANT3 22
x=0 do you want to continue?y
while ch=='y': enter list valuesHRISHANT4 23
l=input("enter list values") do you want to continue?n
f.writelines(l) File Created Successfully!!! with 4 records
ch=input("do you want to continue?") entered
x+=1
print("File Created Successfully!!! with ",x,"records HRISHANT1 20HRISHANT2 21HRISHANT3
entered") 22HRISHANT4 23
f.close()
Q) Write a python program to display writing more than Enter list values --> rishu1
one data into a Text file using writeline. Do you want to continue --> y
Enter list values --> rishu2
with open ("two.txt",'w') as f: Do you want to continue --> y
l=[] Enter list values --> rishu3
ch='y' Do you want to continue --> y
x=0 Enter list values --> rishu4
while ch=='y': Do you want to continue --> y
l=input("Enter list values --> ") Enter list values --> rishu5
f.writelines(l) Do you want to continue --> n
ch=input("Do you want to continue --> ") Files created with 5 records entered!!!
x+=1
print("Files created with", x, "records entered!!!")

Q) Write a python program to display read method in Files Read Succssfully!!!


text files. My first line of code
to enter data into a text file
fr=open("one.txt",'r') we will do binary files later
data=fr.read()
print("Files Read Succssfully!!!")
print(data)
fr.close
Q) Write a python program to display the use readlines My first line of code
method in a text file and count the number of files read. to enter data into a text file
we will do binary files later
fr=open("one.txt",'r') Files Read Successfully With 3 Records
data=fr.readline()
ctr=0
while data:
print(data)
data=fr.readline()
ctr+=1
print("Files Read Successfully With", ctr, "Records")
fr.close()
Q) Write a python program to readlines method in text ['My first line of code \n', 'to enter data into
file. a text file \n', 'we will do binary files later \n']
Lines Read Successfully!!!
fr=open("one.txt",'r')
data=fr.readlines()
print(data)
print("Lines Read Successfully!!!")
fr.close
Q) Write a python program to use replace method with Original Data --> My first line of code
argument in text files. to enter data into a text file
we will do binary files later
fr=open("one.txt",'r')
fw=open("two.txt",'w') Modified Data -->
nd=' ' My@first@line@of@code@
data=fr.read() to@enter@data@into@a@text@file@
print("Original Data --> ", data) we@will@do@binary@files@later@
print("Modified Data --> ", data.replace(' ','@'))
for i in data: Modified String --> My#first#line#of#code#
if i==' ': to#enter#data#into#a#text#file#
nd+='#' we#will#do#binary#files#later#
else:
nd+=i
print("Modified String --> ",nd)
fw.write(nd)
fr.close()
fw.close()
Q) Write a python program to count the number of My first line of code
consonants in a text file. to enter data into a text file
f=open("one.txt",'r') we will do binary files later
data=f.read()
sp,c,d,v=0,0,0,0 String --> My first line of code
L=len(data) to enter data into a text file
for i in data: we will do binary files later
print(i,end=' ')
if i in ("aeiouAEIOU"): Total number of characters --> 86
v+=1 Total number of consonants --> 39
elif i.isalpha(): Total number of vowels --> 26
c+=1 Total number of digits --> 0
elif i.isdigit(): Total number of special chararcters --> 21
d+=1
else:
sp=L-(c+d+v)
print("\n String --> ", data)
print("Total number of characters -->", L)
print("Total number of consonants -->", c)
print("Total number of vowels -->", v)
print("Total number of digits -->", d)
print("Total number of special chararcters -->", sp)
Q) Write a python program for counting number of words Contents of the file are
in a text file. My first line of code
to enter data into a text file
f=open("one.txt",'r') we will do binary files later
data=f.read()
l=data.split() Number of words are --> 18
w=len(l)
print("Contents of the file are \n", data)
print("Number of words are --> ", w)
Q) Write a python program for counting number of ‘my’ Original File --> My first line of code
and 'file' in a text file. to enter data into a text file
we will do binary files later
f=open("one.txt",'r+')
data=f.read() Modified file --> MyMyfirstline
t1,t2=0,0 Ofcodetoenterdataintoatext
l=data.split() FILEfilewewilldobinaryfileslater
New_l=' ' Number of file --> 1
for w in l: My --> 1
if w == 'file': Total number of occurances --> 2
t1+=1
New_l+=w.upper()
elif w == 'My':
t2+=1
New_l+=w
New_l+=w
print("Original File --> ",data)
print("Modified file --> ",New_l)
print("Number of file --> ",t1)
print("My --> ",t2)
print("Total number of occurances --> ",t1+t2)
Q) Write a python program to count and display the lines 1 Line read= My first line of code
beginning with 'I'.
fr=open("one.txt",'r') 2 Line read= to enter data into a text file
fw=open("TWO.txt",'a')
ctr,ctr2=0,0 3 Line read= we will do binary files later
data=fr.readline()
while data:
ctr2+=1 Number of lines beginning with I= 0
print(ctr2,"Line read=",data) Lines written successfully!!!
if data[0]=='I':
print("Line beginning with I --> ",data)
fw.write(data)
ctr+=1
data=fr.readline()
fr.close()
fw.close()
print("\n Number of lines beginning with I=",ctr)
print("Lines written successfully!!!")
Q) Write a python program for creating a Enter admission number:123
dictionary and writing contents into a binary file. {'123': ['Saumya', 93768392,, 'Lodi
colony']}
defBF_dict(): Match found and displayed successfully!
import pickle
fr=open("dict.dat","rb")
ch="y"
count=0
admno=input("Enter admission number:")
try:
while True:
count+=1
dl=pickle.load(fr)
if admno in dl:
print(dl)

except EOFError:
print("Match found and displayed successfully!")
fr.close()
BF_dict()
Q) Write a python program for creating a Enter admission number:123
dictionary and writing contents into a binary file. Enter name:Saumya
Enter phone number:93768392
defBF_dict(): Enter address:Lodi colony
import pickle Do you want to continue?(y/n)y
fw=open("dict.dat","ab") Enter admission number:234
fr=open("dict.dat","rb") Enter name:Shruti
d1={} Enter phone number:89374663
ch="y" Enter address:AnandVihar
ctr=count=0 Do you want to continue?(y/n)n
while ch=="y" or ch=="Y": Written 2 Records
ctr+=1 Reading from the file
ad=input("Enter admission number:") Record 1 : {123: ['Saumya', 93768392,
name=input("Enter name:") 'Lodi colony']}
pn=int(input("Enter phone number:")) Record 2 : {234: ['Shruti', 89374663,
add=input("Enter address:") 'AnandVihar']}
d1={admno:[name,pn,add]} 2 Records read and displayed
pickle.dump(d1,fw) successfully!
ch=input("Do you want to continue?(y/n)")
fw.close()
print("Written",ctr,"Records")
print("Reading from the file")
try:
while True:
count+=1
dl=pickle.load(fr)
print("Record",count,":",dl)
except EOFError:
print(count-1,"Records read and displayed
successfully!")
fr.close()
BF_dict()
Q) Write a python program for writing into csv Enter st record :
file. Roll Number --> 23
Enter name --> Hrishant Tripathi
import csv Enter marks --> 98
f=open("St.csv",'a+') Enter st record :
sw=csv.writer(f) Roll Number --> 31
sw.writerow(["Rn","Name","Marks"]) Enter name --> Naman
for i in range(2): Enter marks --> 98
print("Enter st record :")
r=int(input("Roll Number --> "))
n=input("Enter name --> ")
m=float(input("Enter marks --> "))
sr=[r,n,m]
sw.writerow(sr)
f.close()
Q) Write a python program for reading and Contents of the CSV file St.csv
displaying the contents from a csv file. ['Rn', 'Name', 'Marks']
['23', 'Hrishant Tripathi', '98.0']
#import C-write ['31', 'Naman', '98.0']
import csv
with open("St.csv",'r',newline='\r\n') as f:
cr=csv.reader(f)
print("Contents of the CSV file St.csv")
for rec in cr:
print(rec)
Q) Write a python code to demonstrate ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Implementing stack using list.

stack =["Amar", "Akbar", "Anthony"]


stack.append("Ram")
stack.append("Iqbal")
print(stack)
Q) Write a python program to display stack 1.Push
implementation to perform push(add) and 2.Pop
pop(delete) operations. 3.Display
Enter choice...2
def pstack(): Empty stack
s=[] Continue...y
ch='y' Enter choice...1
print("1.Push") Enter element to add to stack -->11
print("2.Pop") Continue...y
print("3.Display") Enter choice...1
while ch=='y' or ch=='Y': Enter element to add to stack -->12
c=int(input("Enter choice...")) Continue...y
if c == 1 : Enter choice...1
ele=input("Enter element to add to stack -->") Enter element to add to stack -->14
s.append(ele) Continue...y
elif c == 2 : Enter choice...3
if (s==[]): 14 -->
print("Empty stack") 12 -->
else: 11 -->
print("Deleted element ",s.pop()) Continue...y
elif c == 3 : Enter choice...2
l=len(s) Deleted element 14
for i in range(l-1,-1,-1): Continue...n
print(s[i], " --> ")
else:
print("Invalid Input")
ch=input("Continue...")
pstack()
Q) Write a python project to count the number of enter the word --> jInglE All The ways
vowels in a line and to display them in a list. YoU Are GreAT
['I', 'E', 'A', 'e', 'a', 'o', 'U']
v=['a','e','i','o','u'] The number of different vowels in the
word jInglE All The ways YoU Are
w=input("enter the word ") GreAT are 7

s=[]

for letter in w:

if letter in v:

if letter not in s:

s.append(letter)
print(s)

print("The number of different vowels in the


word",w,"are",len(s))

Q) Write a python program for reversing a word in Reversing each word in a string using -->
a string. STRING CONCATANATION
METHOD
# The word is "nohtyP gnimmargorP" 1. Reversed String -->
str1="Python Programming" REVERSE EACH WORD USING
l1=str1.split() STACK IMPLEMENTATION
str2=' ' Original String --> Python Programming
print("Reversing each word in a string using --> Reversed String --> nohtyP
STRING CONCATANATION METHOD") gnimmargorP
for i in l1:
for j in range(len(i)-1,-1,-1):
str2+=i[j]
str2=' '
print("1. Reversed String --> ", str2)
print("REVERSE EACH WORD USING STACK
IMPLEMENTATION")
revs=[]
for w in l1:
for j in range(len(w)-1,-1,-1):
revs.append(w[j])
revs.append(' ')
frevs=''.join(revs)
print("Original String --> ",str1)
print("Reversed String --> ",frevs)
Q) WAP to implement a stack with Book Detail 1. Enter Details
2. Delete Details
def isempty(a): 3. Display Details
Enter Choice...1
if a==[]: Enter Book number --> 10
Enter book name --> HG WELLS
return True Continue...?Y
Enter Choice...1
else: Enter Book number --> 11
Enter book name --> MARK TWAIN
return False Continue...?y
Enter Choice...1
def s_push(a,item): Enter Book number --> 12
Enter book name --> CHARLES
a.append(item) DICKEN
Continue...?y
def s_pop(a): Enter Choice...2
Remove item is --> (12, 'CHARLES
if isempty(a): DICKEN')
Continue...?y
print("Underflow") Enter Choice...3
(11, 'MARK TWAIN')
ele=None (10, 'HG WELLS')
Continue...?n
else:

ele=a.pop()

return ele

def isdisplay(a):

if isempty(a):

print('No element')

else:

for i in a[::-1]:

print(i)

def main():

stack=[]
ch='y'

print("1. Enter Details")

print("2. Delete Details")

print("3. Display Details")

while ch=='y' or ch=="Y":

c=int(input("Enter Choice..."))

if c==1:

bno=int(input("Enter Book number --> "))

bname=input("Enter book name --> ")

bo=(bno,bname)

s_push(stack,bo)

elif c==2:

item=s_pop(stack)

print("Remove item is --> ",item)

elif c==3:

isdisplay(stack)

else:

print("Invalid Option Entered!!!")

ch=input("Continue...?")

main()

Q) Write a python program to generate 5 no. and Enter the number of items in list5
enter them in a list. Enter the lower limit10
Enter the upper limit20
import random [18, 19, 17, 15, 12]
def Rand(start,end,num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
num=int(input("Enter the number of items in list"))
start=int(input("Enter the lower limit"))
end=int(input("Enter the upper limit"))
print(Rand(start,end,num))
Q) Write a python program to enter a Fibonacci How many terms? 10
Series of n terms. Fibonacci sequence:
0
nterms = int(input("How many terms? ")) 1
n1, n2 = 0, 1 1
count = 0 2
if nterms <= 0: 3
print("Please enter a positive integer") 5
8
elif nterms == 1:
13
print("Fibonacci sequence upto",nterms,":")
21
print(n1)
34
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Q) Write a python program to enter a number and Enter a number whose factorial you want
find its factorial. to find5
The factorial of 5 is 120
num=int(input("Enter a number whose factorial you
want to find"))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Q) Write a python program to read a text file and cut
display the words shorter than 4 letters. the
is
def DISPLAYWORDS():
c=0
file=open("STORY.TXT",'R')
line=file.read()
word=line.split()
for w in word:
if len(w)<4:
print(w)
file.close()

Q) Write a function which modifies the global Python is great!


variable 's'. Python
def f(): Python
global s
print(s)
s = "Python"
print(s)

# Global Scope
s = "Python is great!"
f()
print(s)

Q) WAP for creating database using python. ('11c',)


('12c',)
import mysql.connector ('information_schema',)
mydb=mysql.connector.connect(host="localhost",use ('mydatabase',)
r="root",password="tiger") ('mysql',)
print(mydb) ('performance_schema',)
mycursor.execute("show databases") ('sys',)
print("Data Type of mycursor() is :",type(mycursor)) ('tictactoe',)
for c in mycursor:
print(c)
Q)WAP to create a sql table student with fields as :
Rno,admno,name ,cl_s,tot_m

import mysql.connector
mydb=mysql.connector.connect(host="localhost",use
r="root",password="tiger",database="12 C")
mycursor.execute("show tables")
print("TABLES IN DATABASE 12C")
for c in mycursor:
print(c)
print("STRUCTURE OF TABLE STUDENTS")
mycursor.execute("DESC student")
for c in mycursor:
print(c)
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
  print(x)
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE
customers (name VARCHAR(255),
address VARCHAR(255))"

Q) WAP to enter information and display the


contents of the sql file.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",use
r="root",password="tiger",database="12C")
mycursor=mydb.cursor()
ch='y'
while ch=='y' or ch=='Y':
v1=int(input("Add Rno.-->"))
v2=input("Name-->")
v3=input("Cl_S-->")
v4=float(input("TotM-->"))
sql1="INSERT INTO student values(%s,%s,%s,%s)"
info=(v1,v2,v3,v4)
mycursor.execute(sql1, info)
ch=input("Do you want to continue?(y/n)-->")
mydb.commit()
print(mycursor.rowcount,"Row Inserted")
print("DISPLAY THE CONTENTS OF THE TABLE")
mycursor.execute("select * from students")
myrec=mycursor.fetchall()
for r in myrec:
print(r)
def facto(num):
if num<0:
print("Sorry, factorial don't exist for negative
integers!")
elif num==0:
return 1
else:
for i in (1,num+1):
return(num * facto(num-1))

fact=int(input("Enter the number whose factorial


you want to find"))
fac = facto(fact)
print(fac)

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE
mydatabase")
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers
(id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), address VARCHAR(255))")
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()
sql = "INSERT INTO customers (name,
address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record
inserted.")

Q1. Write a method /function countlines_et () Q2. Write a function that counts the number of
in python to read lines from a text file report.txt, “Me” or “My” words present in a text file”
and COUNT those lines which are starting either story1.txt.
with ‘E’ and starting with ‘T’ respectively. And If the “story1.txt” content are as follows:
display the Total count separately. My first book was Me and My Family. It gave me
For example: if REPORT.TXT consists of chance to be known to the world.
“ENTRY LEVEL OF PROGRAMMING CAN BE The output of the function should be:
LEARNED FROM USEFUL FOR VARIETY OF Count of Me/My in file: 4
USERS.” Solution:
Then, Output will be: No. of Lines with E: 1 def displayMeMy():
No. of Lines with T: 1 num=0
Solution: f=open("story1.txt","rt")
def countlines_et(): N=f.read()
f=open("report.txt",'r') M=N.split()
lines=f.readlines() for x in M:
linee=0 if x=="Me" or x== "My":
linet=0 print(x)
for i in lines: num=num+1
if i[0]=='E': f.close()
linee+=1 print("Count of Me/My in file:",num)
elif i[0]=='T': displayMeMy()
linet+=1 OR
print("No.of Lines with E:",linee) Write a function count_A_M(), which should read
print("No.of Lines with T:",linet) each character of a text file STORY.TXT, should
countlines_et() count and display the occurrence of alphabets A
OR and M (including small cases a and m too).
Write a method/function show_todo():in python Example: If the file content is as follow: Updated
to read contents from a text file abc.txt and display information As simplified by official websites.
those lines which have occurrence of the word “ The count_A_M():function should display the
TO” or “DO” output as:
For example: If the content of the file is A or a:4 M or m:2
“THIS IS IMPORTANT TO NOTE THAT SUCCESS IS Solution:
THE RESULT OF HARD WORK WE ALL ARE def count_A_M():
EXPECTED TO DO HARD WORK. AFTER ALL f=open("story1.txt","r")
EXPERIENCE COMES FROM HARDWORK.” A,M=0,0
The method/function should display” r=f.read()
THIS IS IMPORTANT TO NOTE THAT SUCCESS IS for x in r:
THE RESULT OF HARD WORK. if x[0]=="A" or x[0]=="a" :
WE ALL ARE EXPECTED TO DO HARD WORK. A=A+1
Solutions: elif x[0]=="M" or x[0]=="m":
def show_todo(): M=M+1
f=open("abc.txt",'r') f.close()
lines=f.readlines() print("A or a: ",A,"\t M or m: ",M)
for i in lines:
if "TO" in i or "DO" in i:
print(i)
show_todo()

Consider a binary file stock.dat that has the Q4. A binary file “Book.dat” has structure [BookNo,
following data: OrderId, MedicineName,Qty and Book_Name, Author, Price].
Price of all the medicines of wellness medicos, a.Write a user defined function CreateFile() to
write the following functions: input data for a record and add to Book.dat.
a)AddOrder() that can input all the medicine b. Write a function CountRec(Author) in Python
orders. which accepts the Author name as parameter and
b)DisplayPrice() to display the details of all the count and retum number of books by the given
medicine that have Price. Author are stored in the binary file “Book.dat”.
Solution: import pickle
import pickle def CreateFile():
def AddOrder(): fobj=open("Book.dat","ab")
f=open("Stock.dat",'ab') BookNo=int(input("Book Number : "))
OrderId=input("Enter Order Id") Book_name=input("Name :")
MedicineName=input("Enter Medicine Name") Author = input("Author: ")
Qty=int(input("Enter Quantity:")) Price = int(input("Price : "))
Price=int(input("Enter Price:")) rec=[BookNo,Book_Name,Author,Price]
data=[OrderId,MedicineName,Qty,Price] pickle.dump(rec,fobj)
pickle.dump(data,f) fobj.close()
f.close() def CountRec(Author):
AddOrder() fobj=open("Book.dat","rb")
def DisplayPrice(): num = 0
f=open("Stock.dat",'rb') try:
try: while True:
while True: rec=pickle.load(fobj)
data=pickle.load(f) if Author==rec[2]:
if data[3]>500: num = num + 1
print(data[0],data[1],data[2],data[3],sep="\t") except:
except: fobj.close()
f.close() return num
DisplayPrice() Q6. A binary file named “TEST.dat” has some
Q5. Create a binary file funandfood.dat that can records of the structure [TestId, Subject,
store details of rides such as Ticketno, Ridename, MaxMarks, ScoredMarks]
No_ofpersons, and price with the help of Write a function in Python named
AddRides() function and write another python DisplayAvgMarks(Sub) that will accept a subject
function display Total to display total amount of as an argument and read the contents of TEST.dat.
each ticket. Also count total number of tickets sold. The function will calculate & display the Average
Solution: of the ScoredMarks of the passed Subject on
import pickle # to use binary file screen.
def AddRides(): Solution:
f=open("funandfood.dat",'ab') def DisplayAvgMarks(sub):
Ticketno=input("Enter Ticket Number") f=open("TEST.dat","rb")
RideName=input("Enter The Name of Ride") count=0
No_ofperson=int(input("Enter no of Persons")) sum=0
Price=int(input("Enter Price:")) try:
data=[Ticketno,RideName,No_ofperson,Price]
pickle.dump(data,f)
f.close()
AddRides()
def Display Total():
f=open("funandfood.dat",'rb')
total=0
count=0

maxsize=5
top=-1
#-------------
def pop(stack):
global top
if (isEmpty(stack)):
print("\n Stack is UnderFlow \n")
else:
n=stack[top]
stack.pop()
print("Removed Element ",n)
top=top-1
def push(stack):
global top
if (isFull(stack)):
print("\n Stack is OverFlow \n ")
else:
n=int(input("\nEnter an element to push :"))
top=top+1
stack.append(n)
def traverse(stack):
if (isEmpty(stack)):
print("Stack is Empty ")
else:
for i in stack:
print(i,end=" ")
def peak(stack):
global top
return stack[top]
def isFull(stack):
global maxsize
if (top==maxsize-1):
return True
else:
return False
def isEmpty(stack):
if (top==-1):
return True
else:
return False
#********** Main Program ************
stack=[]
a=True
while a:
print("\n1. Stack Push Operation ")
print("2. Stack Pop Operation ")
print("3. Show Peak / Top Position ")
print("4. Traverse / Show Stack ")
print("5. Exit ")
ch=int(input("Enter Choice :"))
if ch == 1:
push(stack)
elif ch == 2:
pop(stack)
elif ch == 3:
print("\n Peak Position ",peak(stack))
print('Top is ', top)
elif ch == 4:
traverse(stack)
elif ch == 5:
a=False
else:
print('Please enter a valid choice ‘)

You might also like