Assignment Holiday Homework
Assignment Holiday Homework
1. What is the difference between Actual argument and Format argument? Explain with example
2. What is positional argument? Give example
3. What is the use of global keyword used in a function with the help of suitable example
4. Is return statement is compulsory in python function? How many values a return statement can return at a
time? If return statement is not used inside a function, what will be the return value of the function ?
5. Trace the flow of execution of the following program
i. def increment (x)
ii. x=x+1
iii.
iv. # main program
v. X=3
vi. print (x)
vii. increment (x)
viii. print(x)
6. What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables A and B.
import random
AR=[20,30,40,50,60,70,80,90]
A =random.randint(1,4)
B =random.randint(3,7)
for K in range(A, B +1):
print (AR[K],end=”#“)
(i) 30#40#50# (ii) 30#40#50#60# (iii) 50#60#70# (iv) 40#50#70#
7. Give the output of the following
x=3
def myfunc():
global x
x+=2
print(x, end=' ')
print(x, end=' ')
myfunc()
print(x, end=' ')
8. Write output of the following program
def func(x,y=10):
if (x%y==0):
x=x+1
return x
else:
y=y-1
return y
p,q=20,23
q=func(p,q)
print(p,"#",q)
p=func(q)
print(p,"#",q)
9. Write a function Swap(Arr,n ) in Python, which accepts a list Arr of numbers swaps all adjacent elements
of list .
Sample Input Data of the list Arr= [ 10,20,30,40,12,11] Output Arr = [20,10,40,30,11,12]
10. Ram , python programmer ,is working on a project which require him to define a function interest. He
define it as
def interest (Principal ,Rate= 0.15,time) :
But this code is not working, help him to identify the error in the above function and also correct it
11. What is the difference between local and global variable explain with example
14. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as argument to
the function. The function returns another list named ‘indexList’ that stores the indices of all four lettered
word of L.
For example:If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
15. Write a function LeftShift(Numlist, n) in Python, which accepts a list Numlist of numbers and n is a
numeric value by which all elements of the list are shifted to left.
Sample input data of the list : Numlist = [10, 20, 30, 40, 50, 60, 70], n=2
Output Numlist = [30, 40, 50, 60, 70, 10, 20]
16. Find the output of the following
def ChangeVal(M,N):
for i in range(N):
if M[i] %5 == 0:
M[i] //=5
if M[i] %3 == 0:
M[i] //=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
17. What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variable number.
String = “CBSEONLINE”
Number = random.randint(0,3)
N=9
while String[N] ! = ‘L’ :
print (String[N] + String[Number] + “#” , end = ‘ ‘ )
Number = Number + 1
N = N-1
a. ES#NE#IO# ii) LE#NO#ON# iii) NS#IE#LO# iv) ES#NE#IS#
ASSIGNMENT FILE HANDLING
1. Write a program in python that defines and calls the user defined function :
Courier_add() : It takes the values from the user and adds the details to the CSV file courier.csv.
Each record consist of a list with field element as Cid, Sname, Source and
destination to store courier id ,senders name ,source and destination address
respectively.
Courier_search() : takes the destination as input and display all the courier records going to that
destination
2. Write a program in python that defines and calls the user defined function :
Add_book() : takes the details of the books and add them to a CSV file Book.csv. Each record
consist of a list with field element as B_id ,B_name and Pub to store book id, book
name and publisher respectively
Search_book() : take publisher name as input and count and display number of books published by
them.
3. Write a Program in Python that defines and calls the following userdefined functions:
ADD() – To accept and add data of an employee to a CSV file‘record.csv’. Each record consists of a
list with field elements as empid, name and salary to store employee id, employe ename
and employee salary respectively.
COUNTR() – To count the number of records present in the CSVfile named ‘record.csv’.
4. Write a Program in Python that defines and calls the following user defined functions:
A csv file "PATIENTS.csv" has structure [PID, NAME, DISEASE].Write the definition of a function
Countrec() in Python that would read contents of the file "PATIENTS.csv" and display the details of
those patients who have the DISEASE as 'COVID-19'. The function should also display the total number
of such patients whose DISEASE is 'COVID-19'.
5. A binary file “Toy.dat” has structure [TID, Toy, Status, MRP].
a) Write a user defined function CreateFile() to input data for a record and add to Toy.dat.
b) Write a function OnOffer() in Python to display the detail of those Toys, which has status as “ON
OFFER” from Toy.dat file.
6. A binary file “ITEMS.DAT” has structure (ID, GIFT, Cost). Write a function to write more items in
ITEM.DATWrite a function Economic() in Python that would read contents of the file “ITEMS.DAT” and
display the details of those ITEMS whose cost is greater then 2500
7. Tarun is a student, who wants to make a python program for Sports Department . He is using binary
file operations with the help of two user defined functions/modules.
(a) New_Entry() to create a binary file called SPORTS.DAT containing sports related material
information- item_id, item_name and item_qty.
(b) Show_Item() to display the item _name and item_qty of items which item_qty less than 5. In
case there is no item available that which quantity is less than 5 the function
displays message.
a) Update_item () to update the name of those tiem whose item id is 102.
8. A text file “PYTHON.TXT” contains alphanumeric text. Write a program that reads this text file and
writes to another file “PYTHON1.TXT” entire file except the numbers or digits in the file.
9. Write a function COUNTLINES( ) which reads a text file STORY.TXT and then count and
display the number of the lines which starts and ends with same letter irrespective of its
case . For example if the content of the text file STORY.TXT is :
The person has a sent a lovely tweet
Boy standing at station is very disturbed
Even when there is no light we can see
How lovely is the situation
The expected output is :
The Number of lines starting with same letter is 2
10. Write a user defined function in python named showlines() which reads contents of a text file named
STORY.TXT and displays every sentence in a separate line.
Assume that a sentence ends with a full stop(. , a question mark(‘?’) or an exclamation(!)
For example, if the content of file is :
Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were
right! So, what else did our parents tell?
Then the function should display the file content as follows:
Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell?
11. Write a function reverseFile()in Python, which should read the content of a text file
“TESTFILE.TXT” and display all its line in the reverse order.
Example: If the file content is as follows:
It rained yesterday.
It might rain today.
I wish it rains tomorrow too.
I love Rain.
The RainCount()function should display the output as:
.yadretsey deniar tI
.yadot niar thgim tI
.oot worromot sniar ti hsiw I
12. Assume that a text file named TEXT1.TXT already contains some text written into it ,write a function
named COPY(),that reads the file TEXT1.TXT and create a new file named TEXT2.TXT ,which shall
contain only those words from the file TEXT1.TXT which don’t start with an uppercase vowel(i.e. with
‘A’,’E’,’I’,’O’,’U’) ,for example if the file TEXT1.TXT contains
He can appoint any member of the Lok Sabha
then the file TEXT2.TXT shall contain
He can member of the Lok Sabha
13. Write the definition of a function ChangeGender() in Python, which reads the contents of a text file
"BIOPIC.TXT" and displays the content of the file with every occurrence of the word 'he' replaced by 'she'.
For example, if the content of the file "BIOPIC.TXT" is as follows :
Last time he went to Agra,there was too much crowd, which he did not like.
So this time he decided to visit some hill station.
The function should read the file content and display the output as follows:
Last time she went to Agra, there was too much crowd, which she did not like.
So this time she decided to visit some hill station.
CASE STUDY ASSIGNMENT: FILE HANDLING
1. Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has written the following code
to read the content of file emp.csv and display the employee record whose name begins from “S‟ also
show no. of employee with first letter “S‟ out of totalrecord. As a programmer, help her to successfully
execute the given task.
Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
import _____ # Line-1
def snames():
with open(______) as csvfile: # Line-2
myreader = csv.___ (csvfile, delimiter=",") # Line-3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower() == "s":
print(row[0],",",row[1],",",row[2])
count_s += 1
count_rec += 1
print(count_rec, count_s)
a) What should be written in Line-1?
b) In which mode should Priti open the file to print the data?
c) What should be written in Line-2 and Line-3?
2. Aditya is a Python programmer. He has written a code and created a binary file student.dat with
rollno, name, class and marks. The file contains 10 records. He now has to search record based on
rollno in the file student.dat As a Python expert, help him to complete the following code based on
the requirement given above:
import _______ #Statement 1
def searchrec():
r=int(input('Enter roll no of student to be searched'))
f=open(______________________) # staement2
found=False
try:
while True:
data=_______________ # statement 3
for rec in data:
if r==_______: # staement4
found=True
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
break
except Exception:
f.close()
if found==True:
print('Search successful')
FILE HANDLING
ASSERTION AND REASONING based questions. Mark the correct choice as:
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
1. Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is the
default value of reference_point?
a) 0 b) 1 c) 2 d) 3
2. To specify a different delimiter while writing into csv file, ……. argument is used withcsv.writer().
a) delimit b) delimiter c) delimited d) delimits
3. To cancel the EOL translation in csv file while writing the data __________argument is used with open().
a) newline b) next c) open d) EOL
4. Every record in a CSV file is stored in reader object in the form of a list using which method?
a) writer() b) append() c) reader() d) list()
5. If you are opening a binary file in read mode, then the file must exist otherwise what happens?
a) Compile time error occur c) Run-time error raises
b) Not any error raises d) None of these
6. Is it necessary to have header line as first line in csv file:
a) No b) Yes c) Both Yes and No d) None
7. In which format does the readlines( ) function give the output?
a) Integer type b) list type c) string type d) tuple type
8. Myfile=open(“class.txt”,”r”)
Str=Myfile.read(12)
The above code will be equal to:
a) file(“class.txt”,”r”).read(12) b) Myfile(“class.txt”,”r”).read(12)
b) file(“class.txt”,”r”).myfile.read(12) c) myfile(“class.txt”,”r”).read(12)
9. Identify the error in the following code:
import pickle
mix_data=[‘hundred’,2, [3,4,5]]
with open (‘mixeddata.dat’, ‘rb’) as fout:
pickle.dump(mix_data , fout)
a) Not any error is there b) with open (‘mixeddata.dat’, ‘w’)
c) with open (‘mixeddata.dat’, ‘wb’) d) None of these
10. Suppose the content Rhymes.txt is
Jack & Jill
Went up the hil
What will be the output of the following code ?
F= open(“Rhymes.Txt”)
L=F.readlines()
for i in L:
S=i.split()
print(len(S),end=”#”)
a) 2#4# b) 3#4# c) 2# d) 7#
11. Suppose the content Rhymes.txt is
One, two, three, four, five
Once I caught a fish alive.
F= open(“Rhymes.Txt”)
S=F.read()
print(S.count(’e’,20))
a) 20 b) 1 c) 3 d) 6
Page 1
12. The correct syntax of read() function from text files is:
a. file_object.read() b. file_object(read) c. read(file_object) d. file_object().read
13. Which of the following are the modes of both writing and reading in binary format in file?
a) wb+ b) w c) w+ d) wb
14. A text file student.txt is stored in the storage device. Identify the correct option out of the following options to open
the file in read mode.
i. myfile = open('student.txt','rb') ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r') iv. myfile = open('student.txt')
a) only I b) both i and iv c) both iii and iv d) both i and iii
15. Assume that the position of file pointer is at the beginning of 3rd line in a text file. Which of the following option can
be used to read all remaining lines?
(a) file.read() (b) file.readlines() (c) file.readline() (d) None of these
16. The _________ method of _____ module is used to read data from binary file :
a) read(), binary b) load(), pickle c) dump(), binary d) dump(), pickle
17. Which of the following modes will refer to binary data?
(a) r (b) wb (c) + (d) a
18. The Correct syntax of seek() is:
(a) File_object.seek(offset[,reference_point]) (b) seek(offset[,referece_point])
(c) seek(offset,file_object) (d) seek.file_object(offset)
19. Which of the following is not a correct Python statement to open a text file “Notes.txt” to write content into it?
a) F=open(‘Notes.txt’,’w’) b) F=open(‘Notes.txt’,’a’)
c) F=open(‘Notes.txt’,’A’) d) F=open(‘Notes.txt’,’w+’)
20. Which of the following option is the correct Python statement to read and display the first 10 characters of a text file
“Notes.txt”?
a) F=open(“Notes.txt”); print(F.load(10)) b) F=open(“Notes.txt”); print(F.dump(10))
c) F=open(“Notes.txt”); print(F.read(10)) d) F=open(“Notes.txt”); print(F.write(10))
21. Which of the following commands is used to open a file “c:\test.txt” for reading and writing data in binary format
only.
(a) myfile = open(‘c:\\test.txt’,’rb+’) (b) myfile = open(‘c:\test.txt\’,’wb’)
(c) myfile = open(‘c:\test.txt’,’w+’) (d) myfile = open(‘c:\\test.txt’,’rb’)
22. Which of the following functions do you use to write data in the binary format?
(a) write() (b) output() (c) dump() (d) send()
23. Method used to force python to write the contents of file buffer on to storage file is
a) count() b) read() c) flush() d) True
24. Which of the following is not a function / method of csv module in Python?
a. read() b. reader() c. writer() d. writerow()
25. Select the correct output of the following code Fp.seek(5,1)
a) Move file pointer five character ahead from the current postion
b)Move file pointer five character ahead from the beginning of a file
c)Move file pointer five character behind from the current postion
d)Move file pointer five character behind ahead from the end of a file
Page 2
ASSGNMENT -1 OUTPUT QUESTIONS
for k in my_dict:
sum+=my_dict[k]
print(sum)
print(my_dict)
5. Find the output of the following
def calc(u):
if u%2==0:
return u+10
else:
return u+2
def pattern (M,B=2):
for CNT in range(0,B):
print(calc(CNT),M,end="")
print()
pattern("*")
pattern("#",4)
pattern("@",3)
6. Find the output of the following
L="earn"
X=""
L1=[]
count=1
for i in L:
if i in ['a','e','i','o','u']:
X=X+i.swapcase()
else:
if count%2!=0:
X+=str(len(L[:count]))
else:
X=X+i
count+=1
print(X)
7. Find the output of the following
str = "CBSE Digital India"
for i in range(len(str)-1,0,-1):
if str[i].isupper():
print(str[i].lower(),end="")
if i%2==0:
if str[i].islower():
print(str[i].upper(),end="")
else:
print('$',end="")
8. Find the output of the following
s="Hello2everyone"
n=len(s)