MCQ Fn&file

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

1.

Built-in functions are also known as ________

Ans. Library functions

2. For a function header as follows:

def calc(x,y=20):

Which of the following function calls will give an error?

(a) calc(15,25) (b) calc(x=15,y=25) (c) calc(y=25) (d) calc(x=25)

Ans. (d) calc(x=25)

3. If the following statement is used to read the contents of a text file object F:

x=F.readlines( )

Which of the following is the correct data type of x?

(a) string (b) list (c) tuple (d) dictionary

Ans. (b) list

4. Which of the following command is used to open a file “c:\pat.dat” for writing as well as reading in
binary format only?

(a) fout=open(“c:\pat.dat”,”w”) (b) fout=open(“c:\\pat.dat”,”wb”)

(c) fout=open(“c:\pat.dat”,”w+”) (d) fout=open(“c:\pat.dat”,”wb+”)

Ans. (d) fout=open(“c:\pat.dat”,”wb+”)

5. Suppose the context of “Rhymes.txt” is

Hickory Dickory Dock


The mouse went up the clock
What will be the output of the following Python code?

f=open(“Rhymes.txt”)
l=f.readlines()
x=[“the”,”ock”]
for i in l:
for w in i.split():
if w in x:
print(w,end=”*”)
(a) the* (b) the*the* (c) Dock*the*clock* (d) error

Ans. (b) the*the*

6. What will be the output of the following Python code snippet? 1

total={}
def insert(items):
if items in total:
total[items] += 1
else:
total[items] = 1
insert('Apple')
insert('Ball')
insert('Apple')
print (len(total))

A. 0 B. 1 C. 2 D. 3

Ans : C 2

7. To read the entire remaining contents of the file as a string from a file object infile, we use
____________ 1
a. infile.read(2)
b. infile.read()
c. infile.readline()
d. infile.readlines()
Ans : b infile.read()
8. What is the difference between r+ and w+ modes? 1
a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the
end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at
the end for r+
d) depends on the operating system
Ans: b in r+ the pointer is initially placed at the beginning of the file and the pointer
is at the end for w+
9. Which of the following is the correct syntax of file object ‘fobj’ to write sequence data type using
writelines() function? (1)
(a) file.writelines(sequence) (b) fobj.writelines()
(c) fobj.writelines(sequence) (d) fobj.writeline()
10. The correct syntax of seek() is:
(a) file_object.seek(offset [, reference_point])
(b) seek(offset [, reference_point])
(c) seek(offset, file_object)
(d) seek.file_object(offset)
Ans: (a) file_object.seek(offset [, reference_point])
11. Which of the following mode in file opening statement results or generates an error if the file
does not exist?
(a) r+ (b) a+ (c) w+ (d) None of the above
Ans: (a) r+
12. Which of the following statements correctly explain the function of tell() method?
(a) tells the current position within the file.
(b) tell the name of file.
(c) move the current file position to a different location.
(d) it changes the file position only if allowed to do so else returns an error
Ans: (a) tells the current position within the file.
13. When the file content is to be retained, we can use the ____________ mode
(a) r (b) w (c) a (d) w+
Ans: (c) a
14. .Identify the output of the following python statements 1
import random
for n in range(2,5,2):
print(random.randrange(1,n,end=’*’)
(a)1*3 (b) 2*3 (c) 1*3*4 (d)1*4
Ans: (a)1*3
15. tell() is a method of:
a) pickle module b) csv module c) file object d) seek()
Ans: . c) file-object
Assertion(A): The file access mode ‘a’ is used to append the data in the file.

Reason(R): In the access mode ‘a’ the text will be appended at the end of the existing file. If the file
does not exist, Python will create a new file and write data into it.

Ans. (a) Both A and R are true and R is the correct explanation for A

Assertion(A): Keyword arguments are related to function calls.

Reason(R): When you use keyword arguments in a function call, the caller identifies the arguments
by the values passed.

Ans: (b) Both A and R are true and R is not the correct explanation for A

Assertion - In a function header, any parameter cannot have a default value unless all

parameters appearing on its right have their default values.

Reason - Non- default arguments cannot follow default arguments.

Ans : A Both A and R are true and R is the correct explanation of A.

Assertion - The with statement simplifies the working with files but does not support

exception handling.

Reason – The with statement will automatically close the file after the nested block ofcode.

Ans : D - A is false but R is true.

Assertion (A): Function can take input values as parameters, execute them and return output (if
required) to the calling function with a return statement. (1)

Reason (R): A function in Python can return multiple values.

Note: return multiple values: return a,b,c - return it as tuple . its not revised in the class

Assertion (A): Pickle in Python is primarily used in serializing and deserializing a Python object
structure.

Reason (R): pickle.dump() method is used to write the object in file and pickle.load() method is used
to read the object from pickled file

Note: Serializing=pickling deserializing= unpickling


Assertion (A):- If a text file already containing some text is opened in write mode the previous
contents are overwritten.

Reasoning (R):- When a file is opened in write mode the file pointer is present at the beginning
position of the file

Ans: (a) Both A and R are true and R is the correct explanation for A

Note: When we opened in r+ mode ,eventhough file pointer is at the beginning, when we write after
opening it will not overwrite

Assertion(A):-Built in functions are predefined in the language that are used directly.

Reasoning(R):-print() and input() are built in functions

Ans:(b) Both A and Rare true and R is not the correct explanation for A

Assertion(A):CSV file stands for Comma Separated Values.

Reason(R):CSV files are common file format for transferring and storing data

Ans: (b) Both A and R are true and R is not the correct explanation for A

Explanation: The ability to read , manipulate and write data to and from CSV files using python is a
key skill to master for any data Scientist and Business analysis.

Assertion: The default value of an argument will be used inside a function if we do not pass a value
to that argument at the time of the function call.

Reason: the default arguments are optional during the function call. It overrides the default value if
we provide a value to the default arguments during function calls.

Ans: (a)Both A and R are true and R is the correct explanation for A

Predict the output of the Python code given below:

i.z= 100 Ans. z is: 100


def f( ):
global z New value of global z is: 50
('z is:', z) Value of z is: 50
z=50
print('New value of global z is:', z)
f( )
print('Value of z is:', z)

ii. def COUNT ( ):


s=open ("Quotes.txt", "r")
Ans. 16
f=s.read( )
z=f.split( )
count=0
for i in z:
count=count+1
print (count)
COUNT( )
iii. def test(i, a =[]):
a.append(i)
return a
Ans. [25,32,17]
test(25) #not used returned value mutable datatype
test(32)
s = test(17)
print(s)
iv. def evn(l):
enum=” “
for n in range(len(l)): Ans. arAcdbRa
if n%2==0:
enum+=l[n]
elif n%3==0:
enum+=l[n].upper( )
return enum
print(evn([‘a’,’b’,’r’,’a’,’c’,’a’,’d’,’a’,’b’,’r’,’a’]))
v. a=10
b=20
def change( ): Ans. 10
global b
a=45 56
b=56
change( )
print(a)
print(b)
vi. def Change(s):
k =len(s)
m=" " Ans:ipV$$$$$$BIT
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'$'
print(m)
Change('IPv6 128-bit')
vii. Val = 100
def display(N):
global Val
Val = 100 Ans:10000$10000
if N%2==0:
Val = Val ** N
else:
Val = Val * N
print(Val, end="$")
display(2)
print(Val)

viii. def Change(P ,Q=30):


P=P+Q
Q=P-Q 250 # 150
print(P,"#",Q) 250 # 100
return(P) 130 # 100
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
ix. value = 50
def display(N):
global value 50#5
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)

x. a=20
def call():
global a
b=20 20
a=a+b 40
return a
print(a)
call()
print(a)
xi. p,q=8, [8]
def sum(r,s=5): 34@53@[13, 24]
p=r+s
q=[r,s]
print(p, q, sep='@')
sum(3,4)
print(p, q, sep='@')

xii. def Alpha(N1):


while N1:
a=N1.pop()
if a%5>2: 7@[3, 4] 8@[8]
print(a,end='@')
else:
break
NUM=[13,24,12,53,34]
Alpha(NUM); print(NUM)
Write a function called rem_keys( D,keylist) that accepts two parameters: a dictionary called D and a
list called keylist. Function rem_keys(D,keylist) should remove all the keys contained in the passed
keylist from the dictionary D and return the dictionary.
Ans. def rem_keys(D, keylist):
for k in keylist:
if k in D:
del D[k]
return D
D={“k1”:101,”k2”:202,”k3”: 303,”k4”: 404}
keys=[“k1”,”k3”,”k5”]
print(“Original dictionary:”,D)
print(“The keylist:”,keys)
print(“Dictionary after removing keys:”,rem_keys(D,keys))

What is the purpose of using flush() in file handling operations? 5


Sharadhi Patel of class 12 is writing a program to create a CSV file “emp.csv” which will
contain employee code, name and salary of employees. Write a Program in Python that
defines and calls the following user defined functions:
(i) InsRec() – To accept and add data of an employee to a CSV file ‘emp.csv’. Each
record consists of a list with field elements as eid, ename and sal
(ii) search()- To display details of all the employees whose salary is greater than
10000
As a programmer, help him to successfully execute the given task.
Ans : flush() allows the user to send content in file before closing the file. It means when
flush() is used it will clear the buffer and transfer content to file.
import CSV
def InsRec(eid,ename,sal): #to write/add data into the CSV file
fo=open('emp.csv','a')
writer=csv.writer(fo)
writer.writerow([eid,ename,sal])
fo.close()
def search():
fin=open("emp.csv","r",newline='\n')
data=csv.reader(fin)
found=False
print("The Details are")
for i in data:
if ((i[2])>10000):
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
(1 mark for flush() definition
½ mark for importing csv module
1 ½ marks each for correct definition of InsRec() and search()
½ mark for function call statements )
OR
Give one difference between Text file and Binary File
A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i.Write a user defined function CreateFile() to input data for a record and add to
Book.dat .
ii.Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in
the binary file “Book.dat”
Ans :
Text file contains EOL character at the end of every line, there is no such character in
binary file
import pickle
def createFile():
fobj=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()
def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
(1 mark for flush() definition
½ mark for importing csv module
1 ½ marks each for correct definition of InsRec() and search()
½ mark for function call statements)

You might also like