You are on page 1of 70

Python Revision Tour

Class 12 - Computer Science with Python Sumita Arora


Multiple Choice Questions

Question 1

Which of the following is an invalid variable?

1. my_day_2
2. 2nd_day ✓
3. Day_two
4. _2

Question 2

Which of the following is not a keyword?

1. eval ✓
2. assert
3. nonlocal
4. pass

Question 3

Which of the following cannot be a variable?

1._init_
2. in ✓
3. it
4. on

Question 4

Which of these is not a core data type?

1. Lists
2. Dictionary
3. Tuples
4. Class ✓
Question 5

How would you write xy in Python as an expression ?

1. x^y
2. x**y ✓
3. x^^y
4. none of these

Question 6

What will be the value of the expression?


    14 + 13 % 15

1. 14
2. 27 ✓
3. 12
4. 0

Question 7

Evaluate the expression given below if A = 16 and B = 15.


    A % B // A

1. 0.0
2. 0✓
3. 1.0
4. 1

Question 8

What is the value of x?


    x = int (13.25 + 4/2)

1. 17
2. 14
3. 15 ✓
4. 23

Question 9

The expression 8/4/2 will evaluate equivalent to which of the following expressions:

1. 8/(4/2)
2. (8/4)/2 ✓

Question 10

Which among the following list of operators has the highest precedence?

    +, -, **, %, /, <<, >>, |

1. <<, >>
2. ** ✓
3. I
4. %

Question 11

Which of the following expressions results in an error?

1. float('12')
2. int('12')
3. float('12.5')
4. int('12.5') ✓

Question 12

Which of the following statement prints the shown output below?


    hello\example\test.txt

1. print("hello\example\test.txt")
2. print("hello\\example\\test.txt") ✓
3. print("hello\"example\"test.txt")
4. print("hello"\example"\test.txt")

Question 13

Which value type does input() return ?

1. Boolean
2. String ✓
3. Int
4. Float

Question 14

Which two operators can be used on numeric values in Python?


1. @
2. %✓
3. +✓
4. #

Question 15

Which of the following four code fragments will yield following output?

Eina
Mina
Dika
Select all of the function calls that result in this output

1. print('''Eina
\nMina
\nDika''')
2. print('''EinaMinaDika''')
3. print('Eina\nMina\nDika')✓
4. print('Eina
Mina
Dika')

Question 16

Which of the following is valid arithmetic operator in Python :

1. // ✓
2. ?
3. <
4. and

Fill in the Blanks

Question 1

The smallest individual unit in a program is known as a token.

Question 2

A token is also called a lexical unit.

Question 3
A keyword is a word having special meaning and role as specified by programming language.

Question 4

The data types whose values cannot be changed in place are called immutable types.

Question 5

In a Python expression, when conversion of a value's data type is done automatically by the
compiler without programmer's intervention, it is called implicit type conversion.

Question 6

The explicit conversion of an operand to a specific type is called type casting.

Question 7

The pass statement is an empty statement in Python.

Question 8

A break statement skips the rest of the loop and jumps over to the statement following the loop.

Question 9

The continue statement skips the rest of the loop statements and causes the next iteration of the
loop to take place.

Question 10

Python's keywords cannot be used as variable name.

True/False Questions

Question 1

The expression int(x) implies that the variable x is converted to integer.


True

Question 2

The value of the expressions 4/(3*(2 - 1)) and 4/3*(2 - 1) is the same.
True
Question 3

The value of the expressions 4/(3*(4 - 2)) and 4/3*(4 - 2) is the same.
False

Question 4

The expression 2**2**3 is evaluated as: (2**2)**3.


False

Question 5

A string can be surrounded by three sets of single quotation marks or by three sets of double
quotation marks.
True

Question 6

Variables can be assigned only once.


False

Question 7

In Python, a variable is a placeholder for data.


False

Question 8

In Python, only if statement has else clause.


False

Question 9

Python loops can also have else clause.


True

Question 10

In a nested loop, a break statement terminates all the nested loops in one go.
False

Type A: Short Answer Questions/Conceptual Questions

Question 1
What are tokens in Python? How many types of tokens are allowed in Python? Exemplify your
answer.

Answer

The smallest individual unit in a program is known as a Token. Python has following tokens:

1. Keywords — Examples are import, for, in, while, etc.


2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
3. Literals — Examples are "abc", 5, 28.5, etc.
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc.

Question 2

How are keywords different from identifiers?

Answer

Keywords are reserved words carrying special meaning and purpose to the language
compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names
for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not
reserved. They can have letters, digits and underscore. They must begin with either a letter or
underscore. For example, _chk, chess, trail, etc.

Question 3

What are literals in Python? How many types of literals are allowed in Python?

Answer

Literals are data items that have a fixed value. The different types of literals allowed in Python
are:

1. String literals
2. Numeric literals
3. Boolean literals
4. Special literal None
5. Literal collections

Question 4

Can nongraphic characters be used and processed in Python? How? Give examples to support
your answer.

Answer
Yes, nongraphic characters can be used in Python with the help of escape sequences. For
example, backspace is represented as \b, tab is represented as \t, carriage return is represented
as \r.

Question 5

Out of the following, find those identifiers, which cannot be used for naming Variables or
Functions in a Python program:

 Price*Qty
 class
 For
 do
 4thCol
 totally
 Row31
 _Amount

Answer

 Price*Qty ⇒ Contains special character *


 class ⇒ It is a keyword
 4thCol ⇒ Begins with a digit

Question 6

How are floating constants represented in Python? Give examples to support your answer.

Answer

Floating constants are represented in Python in two forms — Fractional Form and Exponent
form. Examples:

1. Fractional Form — 2.0, 17.5, -13.0, -0.00625


2. Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3

Question 7

How are string-literals represented and implemented in Python?

Answer

A string-literal is represented as a sequence of characters surrounded by quotes (single, double or


triple quotes). String-literals in Python are implemented using Unicode.
Question 8

What are operators ? What is their function? Give examples of some unary and binary operators.

Answer

Operators are tokens that trigger some computation/action when applied to variables and other
objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical
negation (not) are a few examples of unary operators. Examples of binary operators are Addition
(+), Subtraction (-), Multiplication (*), Division (/).

Question 9

What is an expression and a statement?

Answer

An expression is any legal combination of symbols that represents a value. For example, 2.9, a +
5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For
example:
print("Hello")
a = 15
b = a - 10

Question 10

What all components can a Python program contain?

Answer

A Python program can contain various components like expressions, statements, comments,
functions, blocks and indentation.

Question 11

What are variables? How are they important for a program?

Answer

Variables are named labels whose values can be used and processed during program run.
Variables are important for a program because they enable a program to process different sets of
data.

Question 12
Describe the concepts of block and body. What is indentation and how is it related to block and
body?

Answer

A block in Python, represents a group of statements executed as a single unit. Python uses
indentation to create blocks of code. Statements at same indentation level are part of same
block/suite and constitute the body of the block.

Question 13

What are data types? How are they important?

Answer

Data types are used to identify the type of data a memory location can hold and the associated
operations of handling it. The data that we deal with in our programs can be of many types like
character, integer, real number, string, boolean, etc. hence programming languages including
Python provide ways and facilities to handle all these different types of data through data types.
The data types define the capabilities to handle a specific type of data such as memory space it
allocates to hold a certain type of data and the range of values supported for a given data type,
etc.

Question 14

How many integer types are supported by Python? Name them.

Answer

Two integer types are supported by Python. They are:

1. Integers (signed)
2. Booleans

Question 15

What are immutable and mutable types? List immutable and mutable types of Python.

Answer

Mutable types are those whose values can be changed in place whereas Immutable types are
those that can never change their value in place.

Mutable types in Python are:

1. Lists
2. Dictionaries
3. Sets

Immutable types in Python are:

1. Integers
2. Floating-Point numbers
3. Booleans
4. Strings
5. Tuples

Question 16

What is the difference between implicit type conversion and explicit type conversion?

Answer

Implicit Type Conversion Explicit Type Conversion

An implicit type conversion is An explicit type conversion is


automatically performed by the compiler user-defined conversion that
when differing data types are intermixed forces an expression to be of
in an expression. specific type.

An explicit type conversion is


An implicit type conversion is performed
specified explicitly by the
without programmer's intervention.
programmer.

Example: Example:
a, b = 5, 25.5 a, b = 5, 25.5
c=a+b c = int(a + b)

Question 17

An immutable data type is one that cannot change after being created. Give three reasons to use
immutable data.

Answer

Three reasons to use immutable data types are:

1. Immutable data types increase the efficiency of the program as they are quicker to access
than mutable data types.
2. Immutable data types helps in efficient use of memory storage as different variables
containing the same value can point to the same memory location. Immutability
guarantees that contents of the memory location will not change.
3. Immutable data types are thread-safe so they make it easier to parallelize the program
through multi-threading.

Question 18

What is entry controlled loop? Which loop is entry controlled loop in Python?

Answer

An entry-controlled loop checks the condition at the time of entry. Only if the condition is true,
the program control enters the body of the loop. In Python, for and while loops are entry-
controlled loops.

Question 19

Explain the use of the pass statement. Illustrate it with an example.

Answer

The pass statement of Python is a do nothing statement i.e. empty statement or null operation
statement. It is useful in scenarios where syntax of the language requires the presence of a
statement but the logic of the program does not. For example,

for i in range(10):
if i == 2:
pass
else:
print("i =", i)

Question 20

Below are seven segments of code, each with a part coloured. Indicate the data type of each
coloured part by choosing the correct type of data from the following type.

(a) int
(b) float
(c) bool
(d) str
(e) function
(f) list of int
(g) list of str

(i)
if temp < 32 :
print ("Freezing")

(ii)

L = ['Hiya', 'Zoya', 'Preet']


print(L[1])

(iii)

M = []
for i in range (3) :
M.append(i)
print(M)

(iv)

L = ['Hiya', 'Zoya', 'Preet']


n = len(L)
if 'Donald' in L[1 : n] :
print(L)

(v)

if n % 2 == 0 :
print("Freezing")

(vi)

L = inputline.split()
while L != ( ) :
print(L)
L = L[1 :]

(vii)

L = ['Hiya', 'Zoya', 'Preet']


print(L[0] + L[1])

Answer

(i) bool
(ii) str
(iii) list of int
(iv) int
(v) bool
(vi) list of str
(vii) str
Type B: Application Based Questions

Question 1

Fill in the missing lines of code in the following code. The code reads in a limit amount and a list
of prices and prints the largest price that is less than the limit. You can assume that all prices and
the limit are positive numbers. When a price 0 is entered the program terminates and prints the
largest price that is less than the limit.

#Read the limit


limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
<write your code here>
#Read the next price
<write your code here>
if max_price > 0:
<write your code here>
else :
<write your code here>

Answer

#Read the limit


limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
if next_price < limit and next_price > max_price:
max_price = next_price
#Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
if max_price > 0:
print("Largest Price =", max_price)
else :
print("Prices exceed limit of", limit);

Question 2a

Predict the output of the following code fragments:

count = 0
while count < 10:
print ("Hello")
count += 1

Answer

Output

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

Question 2b

Predict the output of the following code fragments:

x = 10
y = 0
while x > y:
print (x, y)
x = x - 1
y = y + 1

Answer

Output

10 0
9 1
8 2
7 3
6 4

Explanation

x y Output Remarks

10 0 10 0 1st Iteration
x y Output Remarks

10 0
9 1 2nd Iteration
91

10 0
8 2 91 3rd Iteration
82

10 0
91
7 3 4th Iteration
82
73

10 0
91
6 4 82 5th Iteration
73
64

Question 2c

Predict the output of the following code fragments:

keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False

Answer

Output

100
90
80
70
60
50

Explanation

Inside while loop, the line x = x - 10 is decreasing x by 10 so after 5 iterations of while loop
x will become 40. When x becomes 40, the condition if x < 50 becomes true
so keepgoing is set to False due to which the while loop stops iterating.

Question 2d

Predict the output of the following code fragments:

x = 45
while x < 50 :
print (x)

Answer

This is an endless (infinite) loop that will keep printing 45 continuously.

As the loop control variable x is not updated inside the loop neither there is any break statement
inside the loop so it becomes an infinite loop.

Question 2e

Predict the output of the following code fragments:

for x in [1,2,3,4,5]:
print (x)

Answer

Output

1
2
3
4
5

Explanation

x will be assigned each of the values from the list one by one and that will get printed.

Question 2f
Predict the output of the following code fragments:

for p in range(1,10):
print (p)

Answer

Output

1
2
3
4
5
6
7
8
9

Explanation

range(1,10) will generate a sequence like this [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]. p will be assigned


each of the values from this sequence one by one and that will get printed.

Question 2g

Predict the output of the following code fragments:

for z in range(-500, 500, 100):


print (z)

Answer

Output

-500
-400
-300
-200
-100
0
100
200
300
400
Explanation

range(-500, 500, 100) generates a sequence of numbers from -500 to 400 with each
subsequent number incrementing by 100. Each number of this sequence is assigned to z one by
one and then z gets printed inside the for loop.

Question 2h

Predict the output of the following code fragments:

x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)

Answer

This code generates No Output.

Explanation

The x-y * 2 in range(x-y * 2) is evaluated as below:


    x - y * 2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒0

Thus range(x-y * 2) is equivalent to range(0) which returns an empty sequence — [ ].

Question 2i

Predict the output of the following code fragments:

c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)

Answer

Output

50

Explanation
Outer loop executes 10 times. For each iteration of outer loop, inner loop executes 5 times. Thus,
the statement c += 1 is executed 10 * 5 = 50 times. c is incremented by 1 in each execution so
final value of c becomes 50.

Question 2j

Predict the output of the following code fragments:

x = [1,2,3]
counter = 0
while counter < len(x):
print(x[counter] * '%')
for y in x:
print(y * '* ')
counter += 1

Answer

Output

%
*
* *
* * *
%%
*
* *
* * *
%%%
*
* *
* * *

Explanation

In this code, the for loop is nested inside the while loop. Outer while loop runs 3 times and prints
% as per the elements in x in each iteration. For each iteration of while loop, the inner for loop
executes 3 times printing * as per the elements in x.

Question 2k

Predict the output of the following code fragments:

for x in 'lamp':
print(str.upper(x))
Answer

Output

L
A
M
P

Explanation

The for loop extracts each letter of the string 'lamp' one by one and place it in variable x. Inside
the loop, x is converted to uppercase and printed.

Question 2l

Predict the output of the following code fragments:

x = 'one'
y = 'two'
counter = 0
while counter < len(x):
print(x[counter], y[counter])
counter += 1

Answer

Output

o t
n w
e o

Explanation

Inside the while loop, each letter of x and y is accessed one by one and printed.

Question 2m

Predict the output of the following code fragments:

x = "apple, pear, peach"


y = x.split(", ")
for z in y :
print(z)
Answer

Output

apple
pear
peach

Explanation

x.split(", ") breaks up string x into a list of strings so y becomes ['apple', 'pear', 'peach']. The for
loop iterates over this list and prints each string one by one.

Question 2n

Predict the output of the following code fragments:

x ='apple, pear, peach, grapefruit'


y = x.split(', ')
for z in y:
if z < 'm':
print(str.lower(z))
else:
print(str.upper(z))

Answer

Output

apple
PEAR
PEACH
grapefruit

Explanation

x.split(', ') breaks up string x into a list of strings so y becomes ['apple', 'pear', 'peach',
'grapefruit']. The for loop iterates over this list. apple and grapefruit are less than m (since a and
g comes before m) so they are converted to lowercase and printed whereas pear and peach are
converted to uppercase and printed.

Question 3

Find and write the output of the following python code:

for Name in ['Jayes', 'Ramya', 'Taruna', 'Suraj'] :


print (Name)
if Name[0] == 'T' :
break
else :
print ('Finished!')
print ('Got it!')

Answer

Output

Jayes
Finished!
Ramya
Finished!
Taruna
Got it!

Explanation

The for loop iterates over each name in the list and prints it. If the name does not begin with the
letter T, Finished! is printed after the name. If the name begins with T, break statement is
executed that terminates the loop. Outside the loop, Got it! gets printed.

Question 4(i)

How many times will the following for loop execute and what's the output?

for i in range(-1, 7, -2):


for j in range (3):
print(1, j)

Answer

The loops execute 0 times and the code produces no output. range(-1, 7, -2) returns an empty
sequence as there are no numbers that start at -1 and go till 6 decrementing by -2. Due to empty
sequence, the loops don't execute.

Question 4(ii)

How many times will the following for loop execute and what's the output?

for i in range(1,3,1):
for j in range(i+1):
print('*')

Answer
Loop executes for 5 times.

Output

*
*
*
*
*

Explanation

range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1] so inner loop
executes twice. For second iteration of outer loop j is in range [0, 1, 2] so inner loop executes 3
times. This makes the total number of loop executions as 2 + 3 = 5.

Question 5

Is the loop in the code below infinite? How do you know (for sure) before you run it?

m = 3
n = 5
while n < 10:
m = n - 1
n = 2 * n - m
print(n, m)

Answer

The loop is not infinite. To know this without running it we can analyze how n is changed inside
the loop in the following way:

n=2*n-m

Substituting value of m from m = n - 1,

    n = 2 * n - (n - 1)
⇒n=2*n-n+1
⇒ n = 2n - n + 1
⇒n=n+1

Therefore, inside the loop n is incremented by 1 in each iteration. Loop condition is n < 10 and
initial value of n is 5. So after 5 iterations, n will become 10 and the loop will terminate.

Type C: Programming Practice/Knowledge based Questions


Question 1

Write a program to print one of the words negative, zero, or positive, according to whether
variable x is less than zero, zero, or greater than zero, respectively

Solution

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

if x < 0:
print("negative")
elif x > 0:
print("positive")
else:
print("zero")

Output

Enter x: -5
negative

Enter x: 0
zero

Enter x: 5
positive

Question 2

Write a program that returns True if the input number is an even number, False otherwise.

Solution

x = int(input("Enter a number: "))

if x % 2 == 0:
print("True")
else:
print("False")

Output

Enter a number: 10
True

Enter a number: 5
False

Question 3

Write a Python program that calculates and prints the number of seconds in a year.

Solution

days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)

Output

Number of seconds in a year = 31536000

Question 4

Write a Python program that accepts two integers from the user and prints a message saying if
first number is divisible by second number or if it is not.

Solution

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))

if a % b == 0:
print(a, "is divisible by", b)
else:
print(a, "is not divisible by", b)

Output

Enter first number: 15


Enter second number: 5
15 is divisible by 5

Enter first number: 13


Enter second number: 7
13 is not divisible by 7

Question 5
Write a program that asks the user the day number in a year in the range 2 to 365 and asks the
first day of the year — Sunday or Monday or Tuesday etc. Then the program should display the
day on the day-number that has been input.

Solution

dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",


"SATURDAY", "SUNDAY"]

dayNum = int(input("Enter day number: "))


firstDay = input("First day of year: ")

if dayNum < 2 or dayNum > 365:


print("Invalid Input")
else:
startDayIdx = dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1

if currDayIdx >= 7:
currDayIdx = currDayIdx - 7

print("Day on day number", dayNum, ":", dayNames[currDayIdx])

Output

Enter day number: 243


First day of year: FRIDAY
Day on day number 243 : TUESDAY

Question 6

One foot equals 12 inches. Write a function that accepts a length written in feet as an argument
and returns this length written in inches. Write a second function that asks the user for a number
of feet and returns this value. Write a third function that accepts a number of inches and displays
this to the screen. Use these three functions to write a program that asks the user for a number of
feet and tells them the corresponding number of inches.

Solution

def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch

def getInput():
len = int(input("Enter length in feet: "))
return len
def displayLength(l):
print("Length in inches =", l)

ipLen = getInput()
inchLen = feetToInches(ipLen)
displayLength(inchLen)

Output

Enter length in feet: 15


Length in inches = 180

Question 7

Write a program that reads an integer N from the keyboard computes and displays the sum of the
numbers from N to (2 * N) if N is nonnegative. If N is a negative number, then it's the sum of the
numbers from (2 * N) to N. The starting and ending points are included in the sum.

Solution

n = int(input("Enter N: "))
sum = 0
if n < 0:
for i in range(2 * n, n + 1):
sum += i
else:
for i in range(n, 2 * n + 1):
sum += i

print("Sum =", sum)

Output

Enter N: 5
Sum = 45

Enter N: -5
Sum = -45

Question 8

Write a program that reads a date as an integer in the format MMDDYYYY. The program will
call a function that prints print out the date in the format <Month Name> <day>, <year>.

Sample run :
Enter date : 12252019
December 25, 2019

Solution

months = ["January", "February", "March", "April", "May", "June",


"July", "August", "September", "October", "November", "December"]

dateStr = input("Enter date in MMDDYYYY format: ")


monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]

newDateStr = month + ' ' + day + ', ' + year


print(newDateStr)

Output

Enter date in MMDDYYYY format: 12252019


December 25, 2019

Question 9

Write a program that prints a table on two columns — table that helps converting miles into
kilometres.

Solution

print('Miles | Kilometres')
print(1, "\t", 1.60934)
for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)

Output

Miles | Kilometres
1 1.60934
10 16.0934
20 32.1868
30 48.2802
40 64.3736
50 80.467
60 96.5604
70 112.6538
80 128.7472
90 144.8406
100 160.934

Question 10

Write another program printing a table with two columns that helps convert pounds in kilograms.

Solution

print('Pounds | Kilograms')
print(1, "\t", 0.4535)
for i in range(10, 101, 10):
print(i, "\t", i * 0.4535)

Output

Pounds | Kilograms
1 0.4535
10 4.535
20 9.07
30 13.605
40 18.14
50 22.675
60 27.21
70 31.745
80 36.28
90 40.815
100 45.35

Question 11

Write a program that reads two times in military format (0900, 1730) and prints the number of
hours and minutes between the two times.

A sample run is being given below :

Please enter the first time : 0900


Please enter the second time : 1730
8 hours 30 minutes

Solution

ft = input("Please enter the first time : ")


st = input("Please enter the second time : ")

# Converts both times to minutes


fMins = int(ft[:2]) * 60 + int(ft[2:])
sMins = int(st[:2]) * 60 + int(st[2:])

# Subtract the minutes, this will give


# the time duration between the two times
diff = sMins - fMins;

# Convert the difference to hours & mins


hrs = diff // 60
mins = diff % 60

print(hrs, "hours", mins, "minutes")

Output

Please enter the first time : 0900


Please enter the second time : 1730
8 hours 30 minutes

Please enter the first time : 0915


Please enter the second time : 1005
0 hours 50 minutes
Working with functions
1. Aman wants to write a function in python. But he doesn’t know how to start with it! Select the
keyword used to start a function out of the following:
a) function
b) start
c) def
d) fun
Ans. c) def
2. Which of the following is a valid function name?
a) start_game()
b) start game()
c) start-game()
d) All of the above
Ans. a) start_game()
3. Which of the following is not a part of the python function?
a) function header
b) return statement
c) parameter list
d) function keyword
Ans. d) function keyword
4. If the return statement is not used in the function then which type of value will be returned by
the function?
a) int
b) str
c) float
d) None
Ans. d) None
5. The function header contains
a) function name and parameters only
b) def keyword along with function name and parameters
c) return statement only
d) parameter list only
Ans. b) def keyword along with function name and parameters
6. The subprogram that acts on data and returns the value sometimes is known as
a) Function
b) Module
c) Class
d) Package
Ans. a) Function
7. Read the statements:
Statement (A) : A function can perform certain functionality
Statement (B) : A function must return a result value
a) Statement A is correct
b) Statement B is correct
c) Statement A is correct but Statement B is not correct
d) Both are incorrect
Ans. c) Statement A is correct but Statement B is not correct
8. Richa is working with a program where she gave some values to the function. She doesn’t
know the term to relate these values. Help her by selecting the correct option.
a) function value
b) arguments or parameters
c) return values
d) function call
Ans. b) arguments of parameters
9. Mohini wants to know that the symbol : (colon) must be required with which of the following
function part?
a) function header
d) function body
c) return statement
d) parameters
Ans. a) function header
10. Which of the function part contains the instructions for the tasks to be done in the function?
a) function header
d) function body
c) return statement
d) parameters
Ans. b) function body
11. Ananya is trying to understand the features of python functions. She is not understanding the
feature that distributes the work in small parts. Select the appropriate term for her out of the
following:
a) Modularity
b) Reusability
c) Simplicity
d) Abstraction
Ans. a) Modularity
12. Which of the following is not a feature supported by python functions
a) Modularity
b) Reusability
c) Simplicity
d) Data Hiding
Ans. d) Data Hiding
13. Divya wants to print the identity of the object used in the function. Which of the following
function is used to print the same?
a) identity()
b) ide()
c) id()
d) idy()
Ans. c) id()
14. Rashmin is learning the python functions He read the topic types of python functions. He
read that functions already available in the python library is called ___________. Fill
appropriate word in this blank :
a) UDF (User Defined Function)
b) Built-in Functions
c) Modules
d) Reusable Function
Ans. b) Built-in functions
15. Which of the following sentence is not correct for the python function?
a) Python function must have arguments
b) Python function can take an unlimited number of arguments
c) Python function can return multiple values
d) To return value you need to write the return statement
Ans. a) Python function must have arguments
16. Pranjal wants to write a function to compute the square of a given number. But he missed
one statement in the function. Select the statement for the following code:
def sq(n):
____________
print(sq(3))
a) return square of n
b) return n**2
c) return n
d) print(“n**n”)
Ans. b)return n**2
17. Select the proper order of execution for the following code:
A. def diff(a,b):
B. c=a-b
C. print(“The Difference is :”,c)
D. x,y =7,3
E. diff(x,y)
F. print(“Finished”)
a) A -> B -> C -> D -> E -> F
 b) D -> E -> F -> A -> B -> C
c) D -> E -> A -> B -> C -> F
d) E -> B -> C -> D -> A -> F
Ans. c) D -> E-> -> A -> B -> C -> F
18. What is the maximum and minimum value of c in the following code snippet?
import random
a = random.randint(3,5)
b = random.randint(2,3)
c = a + b
print(c)
a) 3 , 5    
b) 5, 8
c) 2, 3
d) 3, 3
Ans. b) 5,8
19. By default python names the segment with top-level statement as __________________
a) def main()
b) main()
c) __main__
d) _main
Ans. c) __main__
20. The order of executing statements in a function is called
a) flow of execution
b) order of execution
c) sequence of execution
d) process of execution
Ans. a) flow of execution
21. In python function, the function calling another function is known as ________________
and the function being called is known _________
a) main, keyword
b) caller, called
c) called, caller
d) executer, execute
Ans. b) caller, called
22. Archi is confused between arguments and parameters. Select the fact about argument and
parameter and solve her doubt
a) arguments are those values being passed and parameters are those values received
b) parameters are those values being passed and arguments are those values received
c) arguments appear in the function header and parameters appear in the function call
d) arguments can have same name and parameters can have value type
Ans. a) arguments are those values being passed and parameters are those values received
23. The value is passed through a function call statement is called _________ and the values
being received in the definition is known as __________
a) formal parameter, actual parameter
b) actual parameter, formal parameter
c) passed parameter, received parameter
d) value parameter, constant parameter
Ans. b) actual parameter, formal parameter
24. The positional parameters are also known as
a) required arguments
b) mandatory arguments
c) Both a and b
d) None of them
Ans. c) Both a and b
25. Which of the following is true about the default argument
a) default values are provided in the function call
b) default values are provided in the function body
c) default values are provided with the return statement
d) default values are provided in the function header
Ans. d) default values are provided in the function header
26. The default valued parameter specified in the function header becomes optional in the
function calling statement.
a) Yes
b) No
c) Not Sure
d) May be
Ans. a) Yes
27. Which of the following function header is correct :
a) def discount(rate=7,qty,dis=5)
b) def discount(rate=7,qty,dis)
c) def discount(rate,qty,dis=5)
d) def discount(qty,rate=7,dis)
Ans. c) def discount(rate,qty,dis=5)
28. Read the following statements and then select the answer:
Statement A: Default arguments can be used to add new parameters to the existing functions
Statement B: Default arguments can be used to combine similar functions into one
a) Statement A is correct
b) Statement B is correct
c) Both are correct
d) Both are incorrect
Ans. c) Both are correct
29. What will be the output of the following code?
def fun(x=10, y=20):
x+=5
y = y - 3
return x*y
print(fun(5),fun())
a) 20, 200
b) 170, 255
c) 85, 200
d) 300, 500
Ans. b) 170, 255
30. What will be the output of the following code?
v = 80
def display(n):
global v
v = 15
if n%4==0:
v += n
else:
v -= n
print(v, end="#")
display(20)
print(v)
a) 80#80
b) 80#100
c) 80#35
d 80#20
Ans. c) 80#35
Watch this video for an explanation:
31. Observe the following lines written for the calling statement and select the appropriate
answer:
ele_bill(past_reading=200,rate=6,current_reading=345)
ele_bill(current_reading=345,rate=6,past_reading=200)
ele_bill(rate=6,past_reading=200,current_reading=345)
a) all lines have errors
b) Only line 1 will execute and the rest will raise an error
c) All lines are correct and no errors
d) only line 3 is correct
c) All lines are correct and no errors
[32] What will be the output of the following:
def Val(m,n):
for i in range(n):
if m[i]<30:
m[i]//=5
elif m[i]%5 == 0:
m[i]//=3
else:
m[i]//=2
l = [25,8,75,12]
Val(l,4)
for i in l:
print(i,end="$")
a) 1$1$2$25$2$
b) 5$1$25$2$
c) 1$4$25$3$
d) 5$2$15$2$
b) 5$1$25$2$
[33] What will be the output of the following code:
def or_cap_update(pl,r,i):
pl['Runs']+=r
pl['Innings']+=i

pl1={'S.No':1,'Name':'K L Rahul','Runs':528,'Innings':12}
pl2={'S.No':2,'Name':'Rituraj Gaikwad','Runs':521,'Innings':13}
or_cap_update(pl1,35,1)
or_cap_update(pl2,35,1)
print(pl1)
print(pl2)
a)
{‘S.No’: 1, ‘Name’: ‘K L Rahul’, ‘Runs’: 35, ‘Innings’: 1}
{‘S.No’: 2, ‘Name’: ‘Rituraj Gaikwad’, ‘Runs’: 35, ‘Innings’: 1}
b)
{‘S.No’: 1, ‘Name’: ‘K L Rahul’, ‘Runs’: 563, ‘Innings’: 13}
{‘S.No’: 2, ‘Name’: ‘Rituraj Gaikwad’, ‘Runs’: 556, ‘Innings’: 14}
c)
{‘S.No’: 1, ‘Name’: ‘K L Rahul’, ‘Runs’: 528, ‘Innings’: 12}
{‘S.No’: 2, ‘Name’: ‘Rituraj Gaikwad’, ‘Runs’: 521, ‘Innings’: 13}
d)
{‘S.No’: 1, ‘Name’: ‘K L Rahul’, ‘Runs’: 528, ‘Innings’: 1}
{‘S.No’: 2, ‘Name’: ‘Rituraj Gaikwad’, ‘Runs’: 521, ‘Innings’: 1}
Ans. b)
{‘S.No’: 1, ‘Name’: ‘K L Rahul’, ‘Runs’: 563, ‘Innings’: 13}
{‘S.No’: 2, ‘Name’: ‘Rituraj Gaikwad’, ‘Runs’: 556, ‘Innings’: 14}
[34] Which of the following variable is defined outside the function?
a) local
b) global
c) enclosed
d) All of thes
Ans. b) global
[35] Observe the following code and select appropriate answers for the given questions:
total = 1
def multiply(l):#Line 1
for x in l:
_______ total #Line2
total *= x

return _______ #Line3 - Reutrn varibale


l=[2,3,4]
print(multiply(_____),end="") # Line4
print(" , Thank you ")
1. Identify the part of function in #Line1?
 Function header
 Function Calling
 Return statement
 Default Argument
2. Which of the keyword is used to fill in the blank for #Line2 to run the program without
error?
 eval
 def
 global
 return
3. Which variable is going to be returned in #Line3
 total
 x
 l
 None
4. Which variable is required in the #Line4?
 total
 x
 l
 None
5. In the line #Line4 the multiply(l) is called __________
 caller
 called
 parameter
 argument
6. In function header multiply(l), l refers to ____________
 caller
 called
 parameter
 argument
7. In function calling multiply(l), l refers to ___________
 caller
 called
 parameter
 argument
8. What will be the output of this code?
 2 3 4 , Thank you
 234 , Thank You
 24 , Thank you
 Thank You
9. Which of the following statement indicates the correct staement for the formal paramter
passing technique?
 multiply(l)
 multiply(l=[23,45,66])
 multiply([23,45,66])
 multiply(23,45,66)
10. Which of the following statement indicates the correct staement for the actual paramter
passing technique?
 multiply(l)
 multiply(l=[23,45,66])
 multiply([23,45,66])
 multiply(23,45,66)
11. Sonal wants to modify the function with the specification of length of list with default
argument statement for the function with the list and 10 elements by default. Which of
the following statement is correct?
 def multiply(n=10,l):
 def multiply(l,n=10):
 def multiply(l,10):
 def myultiply(l=[22,34,56,22,33,12,45,66,7,1])
12. Diya wants to call the function with default argument value in the function to display the
product of list tobject l. Select the correc statement for her to the same.
 multiply(l)
 multiply(10)
 multiply(l,n)
 multiply(n,l)
Answers function Case study based MCQ
1. a) Function Header
2. c) global
3. a) total
4. c) l
5. a) caller
6. b) argument
7. c) parameter
8. d) 24, Thank You
9. a) multiply(l)
10. c) multiply([23,45,66])
11. b) def multiply(l,n=10)
12. a) multiply(l)
Using Python Libraries
1. What will be the output of the following Python code?

from math import factorial

print (math.factorial (5))

(a) 120

(b) Nothing is printed

(c) Error, method factorial doesn't exist in math module

(d) Error, the statement should be: print(factorial(5))

2. What is the order of namespaces in which Python looks for an identifier?

(a) Python first searches the global namespace, then the local namespace and finally the
built-in namespace

(b) Python first searches the local namespace, then the global namespace and finally the
built-in namespace

(c) Python first searches the built-in namespace, then the global namespace and finally the
local namespace

(d) Python first searches the built-in namespace, then the local namespace and finally the
gloab namespace

3. Which of the following is not a valid namespace?

(a) Global namespace

(b) Public namespace

(c) Built-in namespace


(d) Local namespace

4. What will be the output of the following Python code?

#modules

def change (a):

b=[x * 2 for x in a]

print (b)

#module 2

def change (a):

b= (x*x for x in a)

print (b)

from module import change

from module2 import change

#main

s = [1, 2, 3]

change (s)

(a) [2, 4, 6]

(b) [1, 4, 9]

(c)

[2, 4, 6]
[1, 4, 9]

(d) There is a name cash

5. What is the output of the function shown below (random module has already been
imported)?

random.choice('sun')

(a) sun

(b) u

(c) either s, u or n

(d) error

6. What possible output(s) are expected to be displayed on screen at the time of execution
of the program from the following code?

import random

AR = [ 20, 30, 40, 50, 60, 70]

FROM = random.randint (1, 3)

TO = random.randint (2, 4)

for K in range (FROM, TO+1):

print (AR(K), end = "#")

(a) 10#40#70#

(b) 30#40#50#

(c) 50#60#70#
(d) 40#50#70#

7. Which of the statements is used to import all names from a module into the current
calling module?

(a) import

(b) from

(c) import *

(d) dir()

8. Which of the variables tells the interpreter where to locate the module files imported into
a program?

(a) local

(b) import variable

(c) PYTHONPATH

(d) current

9. Which of the following date class function returns the current system date?

(a) day()

(b) today()

(c) month()

(d) year()

10. What is the range of values that random.random() can return?

(a) [0.0, 1.0]


(b) (0.0, 1.0]

(c) (0.0, 1.0)

(d) [0.0, 1.0)

11. A .py file containing constants/variables, classes, functions etc. related to a particular
task and can be used in other programs is called

(a) module

(b) library

(c) classes

(d) documentation

12. The collection of modules and packages that together cater to a specific type of
applications or requirements, is called ____.

(a) module

(b) library

(c) classes

(d) documentation

13. An independent triple quoted string given inside a module, containing documentation
related information is a ____.

(a) Documentation string

(b) docstring

(c) dstring

(d) stringdoc
14. The help statement displays ____ from a module.

(a) constants

(b) functions

(c) classes

(d) docstrings

15. Which command(s) modifies the current namespace with the imported object name?

(a) import <module>

(b) import <module1>, <module2>

(c) from <module> import <object>

(d) from <module> import *

16. Which command(s) creates a separate namespace for each of the imported module?

(a) import <module>

(b) import <module1>, <module2>

(c) from <module> import <object>

(d) from <module> import *

17. Which of the following random module functions generates a floating point number?

(a) random()

(b) randint()

(c) uniform()
(d) all of these

18. Which of the following random module functions generates an integer?

(a) random()

(b) randint()

(c) uniform()

(d) all of these

19. Which file must be a part of a folder to be used as a Python package?

(a) package.py

(b) __init__.py

(c) __package__.py

(d) __module.py__

20. A Python module has ___ extension.

(a) .mod

(b) .imp

(c).py

(d) .mp

ANSWERS

1.( d )

2.  ( b )
3. ( b )

4. ( d )

5. ( c )

6. ( b )

7. ( c )

8.  ( c )

9. ( b )

10. (. d )

11. (. a )

12.  (. b )

13. (. b )

14. (. d )

15. (. c, d )

16. (. a, b )

17.  (. a, c )

18. (. b )

19. (. b )

20.  (. c)

FILE HANDLING
1. Which statement will read 5 characters from a file(file object ‘f’)?
a. f.read()
b. f.read(5)
c. f.reads(5)
d. None of the above
Hide Answer
Ans. b. f.read(5)

Q2. Which function open file in python?


a. open( )
b. new( )
c. Open( )
d. None of the above
Hide Answer
Ans. a. open( )

Q3. Processing of Text file is faster than binary files.(T/F)


a. True
b. False
Hide Answer
Ans. b. False

Q4. Which mode create new file if the file does not exist?
a. write mode
b. append mode
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q5. Which statement will return one line from a file (file object is
‘f’)?
a. f.readline( )
b. f.readlines( )
c. f.read( )
d. f.line( )
Hide Answer
Ans. a. f.readline( )

Q6. readlines() method return _________


a. String
b. List
c. Dictionary
d. Tuple
Hide Answer
Ans. b. List
Q7. EOF stands for _________________
a. End of File
b. End off File
c. End on File
d. End or File
Hide Answer
Ans. a. End of File

Q8. Which function is used to read data from Text File?


a. read( )
b. writelines( )
c. pickle( )
d. dump( )
Hide Answer
Ans. a. read( )

Q9. Which of the following will read entire content of file(file


object ‘f’)?
a. f.reads( )
b. f.read( )
c. f.read(all)
d. f.read( * )
Hide Answer
Ans. b. f.read( )

Q10. Which symbol is used for append mode?


a. ap
b. a
c. w
d. app
Hide Answer
Ans. b. a

Q11. Which of the following options can be used to read the first
line of a text file data.txt?
a. f = open(‘data.txt’); f.read()
b. f = open(‘data.txt’,’r’); f.read(n)
c. myfile = open(‘data.txt’); f.readline()
d. f = open(‘data.txt’); f.readlines()
Hide Answer
Ans. c. myfile = open(‘data.txt’); f.readline()

Q12. File in python is treated as sequence of ________________


a. Bytes
b. Bites
c. bits
d. None of the above
Hide Answer
Ans. a. Bytes

Q13. Which function is used to write data in binary mode?


a. write
b. writelines
c. pickle
d. dump
Hide Answer
Ans. d. dump

Q14. Which function is used to force transfer of data from buffer


to file?
a. flush( )
b. save( )
c. move( )
d. None of the above
Hide Answer
Ans. a. flush( )

Q15. Let the file pointer is at the end of 3rd line in a text file
named “data.txt”. Which of the following option can be used to
read all the remaining lines?
a. f.read( )
b. f.read(all)
c. f.readline( )
d. f.readlines( )
Hide Answer
Ans. d. f.readlines( )

Q16. ____________________ module is used for serializing and de-


serializing any Python object structure.
a. pickle
b. unpickle
c. pandas
d. math
Hide Answer
Ans. a. pickle

Q17. Which of the following error is returned when we try to open


a file in write mode which does not exist?
a. FileNotFoundError
b. FileFoundError
c. FileNotExistError
d. None of the above
Hide Answer
Ans. d. None of the above r

Q18. ______________ function returns the strings.


a. read( )
b. readline( )
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q19. The syntax of seek() is: file_object.seek(offset [,


reference_point])

What is reference_point indicate?


a. reference_point indicates the starting position of the file object
b. reference_point indicates the ending position of the file object
c. reference_point indicates the current position of the file object
d. None of the above.
Hide Answer
Ans. a. reference_point indicates the starting position of the file object

Q20. Identify the invalid mode from the following.


a. a
b. r+
c. ar+
d. w
Hide Answer
Ans. c. ar+

Q21. Which of the following is an invalid mode of file opening?


a. read only mode
b. write only mode
c. read and write mode
d. write and append mode
Hide Answer
Ans. d. write and append mode

Q22. readlines( ) function returns all the words of the file in the
form of List. (T/F)
a. True
b. False
Hide Answer
Ans. b. False

Q23. What is ‘f’ in the following statement?


f=open("Data.txt" , "r")
a. File Name
b. File Handle
c. Mode of file
d. File Handling
Hide Answer
Ans. b. File Handle

Q24. What is full form of CSV


a. Comma Separation Value
b. Comma Separated Value
c. Common Syntax Value
d. Comma Separated Variable
Hide Answer
Ans. b. Comma Separated Value

Q25. Which statement will open file “data.txt” in append mode?


a. f = open(“data.txt” , “a”)
b. f = Open(“data.txt” , “ab”)
c. f = new(“data.txt” , “a”)
d. open(“data.txt” , “a”)
Hide Answer
Ans. a. f = open(“data.txt” , “a”)

Q26. Fill in the blank

import pickle
f=open("data.dat",'rb')
d=_____________________.load(f)
f.close()
a. unpickle
b. pickling
c. pickle
d. pick
Hide Answer
Ans. c. pickle

Q27. Which module to be imported to make the following line


functional?
sys.stdout.write("ABC")
a. system
b. sys
c. stdout
d. stdin
Hide Answer
Ans. b. sys
Q28. What error is returned by the following statement if the file
does not exist?
f=open("A.txt")
a. FileNotFoundError
b. NotFoundError
c. FileNotFound
d. FoundError
Hide Answer
Ans. a. FileNotFoundError

Q29. Which statement will return error?


import pickle
f=open("data.dat",'rb')
d=pickle.load(f)
f.end()
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4
Hide Answer
Ans. d. Statement 4

Q30. Which of the following function takes two arguments?


a. load( )
b. dump( )
c. both of the above
d. none of the above
Hide Answer
Ans. b. dump( )

Q31. Almost all the files in our computer stored as _______ File.


a. Text
b. Binary
c. CSV
d. None of the above
Hide Answer
Ans. b. Binary

Q32. Binary files are not in human readable format.(T/F)


a. True
b. False
Hide Answer
Ans. a. True

Q33. .pdf and .doc are examples of __________ files.


a. Text
b. Binary
c. CSV
d. None of the above
Hide Answer
Ans. b. Binary

Q34. The syntax of seek() is:file_object.seek(offset [,


reference_point]) What all values can be given as a reference
point?
a. 1
b. 2
c. 0
d. All of the above
Hide Answer
Ans. d. All of the above

Q35. There is no delimiter to end a line in binary files.(T/F)


a. True
b. False
Hide Answer
Ans. a. True

Q36. seek( ) method is used for random access to the file.(T/F)


a. True
b. False
Hide Answer
Ans. a. True

Q37. Fill in the blanks in the following code of writing data in


binary files. Choose the answer for statement 1
import ___________   # Statement 1
rec = [ ]
while True:
   rn = int(input("Enter"))
   nm = input("Enter")
   temp = [rn, nm]
   rec.append(temp)
   ch = input("Enter choice (Y/N)")
   if ch.upper == "N":
        break
f = open("stud.dat", "____________")  #statement 2
__________ .dump(rec, f)   #statement 3
_______.close( ) # statement 4

a. csv
b. unpickle
c. pickle
d. load
Hide Answer
Ans. c. pickle
Q38. Refer to the above code and choose the option for
statement2.
a. w
b. w+
c. wb
d. write
Hide Answer
Ans. c. wb

Q39. Refer to the above code (Q 38)and choose the option for
statement 3
a. unpickle
b. write
c. pickle
d. None of the above
Hide Answer
Ans. c. pickle

Q40. Refer to the above code (Q 38)and choose the option for
statement 4.
a. f
b. rec
c. file
d. stud
Hide Answer
Ans. a. f

Q41. The syntax of seek() is:file_object.seek(offset [,


reference_point] What is the default value of reference_point
a. 0
b. 1
c. 2
d. 3
Hide Answer
Ans. a. 0

Q42. _______ function returns the current position of file pointer.


a. get( )
b. tell( )
c. cur( )
d. seek( )
Hide Answer
Ans. b. tell( )
Q43. f.seek(10,0) will move 10 bytes forward from beginning of
file.(T/F)
a. True
b. False
Hide Answer
Ans. a. True

Q44. Which statement will move file pointer 10 bytes backward


from current position.
a. f.seek(-10, 0)
b. f.seek(10, 0)
c. f.seek(-10, 1)
d. None of the above
Hide Answer
Ans. c. f.seek(-10, 1)

Q45. When we open file in append mode the file pointer is at


the _________ of the file.
a. end
b. beginning
c. anywhere in between the file
d. second line of the file
Hide Answer
Ans. a. end

Q46. When we open file in write mode the file pointer is at


the _______ of the file.
a. end
b. beginning
c. anywhere in between the file
d. second line of the file
Hide Answer
Ans. b. beginning

Q47. Write the output of the First Print statements :


f=open("data.txt",'w')
f.write("Hello")
f.write("Welcome to my Blog")
f.close()
f=open("data.txt",'r')
d=f.read(5)
print(d) # First Print Statement
f.seek(10)
d=f.read(3)
print(d) # Second Print Statement
f.seek(13)
d=f.read(5)
print(d) # Third Print Statement
d=f.tell()
print(d) # Fourth Print Statement
a. Hello
b. Hell
c. ello
d. None of the above
Hide Answer
Ans. a. Hello

Q48. Refer to the above code (Q 47) : Write the output of Second
Print Statement
a. om
b. me
c. co
d. None of the above
Hide Answer
Ans. b. me

Q49. Refer to the above code (Q 47) : Write the output of Third
Print Statement
a. e to m
b. e to my
c. to my
d. None of the above
Hide Answer
Ans. c. to my

Q50. Refer to the above code (Q 47) : Write the output of Fourth
Print Statement
a. 17
b. 16
c. 19
d. 18
Hide Answer
Ans. d. 18

Q51. A _____________ is a named location on a secondary storage


media where data are permanently stored for later access.
a. file
b. variable
c. comment
d. token
Hide Answer
Ans. a. file

Q52. A _____ file consists of human readable characters.


a. Binary
b. Text
c. Both of the above
d. None of the above
Hide Answer
Ans. b. Text

Q53. Which of the following file require specific programs to


access its contents?
a. Binary
b. Text
c. CSV
d. None of the above
Hide Answer
Ans. a. Binary

Q54. Which of the following file can be opened in any text editor?
a. Binary
b. Text
c. Both of the above
d. None of the above
Hide Answer
Ans. b. Text

Q55. Each line of a text file is terminated by a special character,


called the ________
a. End of File
b. End of Line
c. End of Statement
d. End of program
Hide Answer
Ans. b. End of Line

Q56. Default EOL character in text file is ________


a. \n
b. \N
c. \t
d. \l
Hide Answer
Ans. a. \n

Q57. Which of the following file can be created in python?


a. Text File
b. Binary File
c. CSV File
d. All of the above
Hide Answer
Ans. d. All of the above

Q58. In which of the following data store permanently?


a. File
b. Variable
c. Both of the above
d. None of the above
Hide Answer
Ans. a. File

Q59. open( ) function takes ____ as parameter.


a. File name
b. Access mode
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q60. Identify the correct statement to open a file:


a. f = open(“D:\\myfolder\\naman.txt”)
b. f = open(“D:\myfolder\naman.txt”)
c. f = open(“D:myfolder#naman.txt”)
d. f = Open(“D:\myfolder\naman.txt”)
Hide Answer
Ans. a. f = open(“D:\\myfolder\\naman.txt”)

Q61. Which of the following are the attributes of file handle?


a. closed
b. name
c. mode
d. All of the above
Hide Answer
Ans. d. All of the above

Q62. Write the output of the following:


>>> f = open("test.txt","w")
>>> f.closed
a. True
b. False
c. Yes
d. No
Hide Answer
Ans. b. False

Q63. Write the output of the following:


>>> f = open("test.txt","w")
>>> f.mode
a. ‘w’
b. ‘r’
c. ‘a’
d. ‘w+’
Hide Answer
Ans. a. ‘w’
Q64. Write the output of the following:
>>> f = open("test.txt","w")
>>> f.name
a. ‘test’
b. ‘test.txt’
c. ‘test.dat’
d. file does not exist
Hide Answer
Ans. b. ‘test.txt’

Q65. Write the output of the following:


>>> f = open("test.txt","w")
>>> f.close()
>>> f.closed
a. True
b. False
c. Yes

Q66. Which of the following attribute of file handle returns


Boolean value?
a. name
b. closed
c. mode
d. None of the above
Hide Answer
Ans. b. closed

Q67. Ravi opened a file in python using open( ) function but


forgot to specify the mode. In which mode the file will open?
a. write
b. append
c. read
d. read and write both
Hide Answer
Ans. c. read

Q68. Which of the following is invalid mode of opening file?


a. r
b. rb
c. +r
d. None of the above
Hide Answer
Ans. d. None of the above

Q69. Which of the following mode will create a new file, if the file
does not exist?
a. ‘a’
b. ‘a+’
c. ‘+a’
d. All of the above
Hide Answer
Ans. d. All of the above

Q70. Which of the following mode will open the file in binary and
read-only mode.
a. ‘r’
b. ‘rb’
c. ‘r+’
d. ‘rb+’
Hide Answer
Ans. b. ‘rb

Q71. Which of the following mode will opens the file in read, write
and binary mode?
a. ‘wb+
b. ‘+wb’
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q72. In the given statement, the file myfile.txt will open


in _______________ mode.
myObject=open(“myfile.txt”, “a+”)
a. append and read
b. append and write
c. append and read and binary
d. All of the above
Hide Answer
Ans. a. append and read

Q73. Ravi opened the file myfile.txt in append mode. In this file
the file object/file handle will be at the __________
a. beginning of the file
b. end of the file
c. second line of the file
d. the end of the first line
Hide Answer
Ans. b. end of the file

Q74. Ravi opened the file myfile.txt in write mode. In this file the
file object/file handle will be at the ______________
a. beginning of the file
b. end of the file
c. second line of the file
d. the end of the first line
Hide Answer
Ans. a. beginning of the file

Q75. Ravi opened the file myfile.txt in read mode. In this file the
file object/file handle will be at the _______________
a. beginning of the file
b. end of the file
c. second line of the file
d. the end of the first line
Hide Answer
Ans. a. beginning of the file

Q76. Ravi opened a file in a certain mode. After opening the file,
he forgot the mode. One interesting fact about that mode is ” If
the file already exists, all the contents will be overwritten”. Help
him to identify the correct mode.
a. read mode
b. write mode
c. append mode
d. binary and read mode
Hide Answer
Ans. b. write mode

Q77. Ram opened a file in a certain mode. After opening the file,
he forgot the mode. The interesting facts about that mode are ” If
the file doesn’t exist, then a new file will be created” and “After
opening file in that mode the file handle will be at the end of the
file” Help him to identify the correct mode.
a. read mode
b. write mode
c. append mode
d. binary and read mode
Hide Answer
Ans. c. append mode

Q78. Which of the following function is used to close the file?


a. close( )
b. end( )
c. quit( )
d. exit( )
Hide Answer
Ans. a. close( )

Q79. open( ) function returns a file object called ______________


a. object handle
b. file handle
c. read handle
d. write handle
Hide Answer
Ans. b. file handle

Q80. Which of the following is the valid way to open the file?
a. with open (file_name, access_mode) as fo:
b. fo = open (file_name, access_mode)
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q81. Rohan opened the file “myfile.txt” by using the following


syntax. His friend told him few advantages of the given syntax.
Help him to identify the correct advantage.
with open ("myfile.txt", "a") as file_object:
a. In case the user forgets to close the file explicitly the file will closed automatically.
b. file handle will always be present in the beginning of the file even in append mode.
c. File will be processed faster
d. None of the above
Hide Answer
Ans. a. In case the user forgets to close the file explicitly the file will closed automatically.

Q82. Mohan wants to open the file to add some more content in
the already existing file. Suggest him the suitable mode to open
the file.
a. read mode
b. append mode
c. write mode
d. All of the above
Hide Answer
Ans. b. append mode

Q83. Aman jotted down few features of the “write mode”. Help
him to identify the valid features.
a. If we open an already existing file in write mode, the previous data will be erased
b. In write mode, the file object will be positioned at the beginning of the file.
c. In write mode, if the file does not exist then the new file will be created.
d. All of the above
Hide Answer
Ans. d. All of the above
Q84. Ananya jotted down few features of the “append mode”.
Help her to identify the valid features.
a. If we open an existing file in append mode, the previous data will remain there.
b. In append mode the file object will be positioned at the end of the file.
c. In append mode, if the file does not exist then the new file will be created.
d. All of the above
Hide Answer
Ans. d. All of the above

Q85. Which of the following methods can be used to write data in


the file?
a. write( )
b. writelines( )
c. Both of the above
d. None of the above
Hide Answer
Ans. c. Both of the above

Q86. Write the output of the following:


>>> f = open("test.txt","w")
>>> f.write("File\n#Handling")
a. 17
b. 16
c. 14
d. 15
Hide Answer
Ans. c. 14

Q87. Which of the following error is returned by the given code:


>>> f = open("test.txt","w")
>>> f.write(345)
a. Syntax Error
b. TypeError
c. StringError
d. Run Time Error
Hide Answer
Ans. b. TypeError

Q88. Which of the following method is used to clear the buffer?


a. clear( )
b. buffer( )
c. flush( )
d. clean( )
Hide Answer
Ans. c. flush( )
Q89. Which of the following method does not return the number
of characters written in the file.
a. write( )
b. writelines( )
c. Both of the above
d. None of the above
Hide Answer
Ans. b. writelines( )

Q90. Fill in the blank in the given code:


>>> fo = open("myfile.txt",'w')
>>> lines = ["Hello \n", "Writing strings\n", "third line"]
>>> fo._____________(lines)
>>>myobject.close()
a. write( )
b. writelines( )
c. writeline( )
d. None of the above
Hide Answer
Ans. b. writelines( )

Q91. In order to read the content from the file, we


can open file in ___________________
a. “r” mode
b. “r+” mode
c. “w+” mode
d. All of the above
Hide Answer
Ans. d. All of the above

Q92. Which of the following method is used to read


a specified number of bytes of data from a data file.
a. read( )
b. read(n)
c. readlines( )
d. reading(n)
Hide Answer
Ans. b. read(n)

Q93. Write the output of the following:


f=open("test.txt","w+")
f.write("File-Handling")
a=f.read(5)
print(a)
a. File-
b. File
c. File-H
d. No Output
Hide Answer
Ans. d. No Output

Q94. Write the output of the following:


f=open("test.txt","w+")
f.write("File-Handling")
f.seek(0)
a=f.read(5)
print(a)
a. File-
b. File
c. File-H
d. No Output
Hide Answer
Ans. a. File-

Q95. Write the output of the following:


f=open("test.txt","w+")
f.write("FileHandling")
f.seek(5)
a=f.read(5)
print(a)
a. andli
b. Handl
c. eHand
d. No Output
Hide Answer
Ans. a. andli

Q96. Write the output of the following:


f=open("test.txt","w+")
f.write("FileHandling")
f.seek(0)
a=f.read()
print(a)
a. File
b. Handling
c. FileHandling
d. No Output
Hide Answer
Ans. c. FileHandling

Q97. Write the output of the following:


f=open("test.txt","w+")
f.write("FileHandling")
f.seek(0)
a=f.read(-1)
print(a)
a. File
b. Handling
c. FileHandling
d. No Output
Hide Answer
Ans. c. FileHandling

Q98. Which of the following method reads one


complete line from a file?
a. read( )
b. read(n)
c. readline( )
d. readlines( )
Hide Answer
Ans. c. readline( )

Q99. Write the output of the following:


f=open("test.txt","w+")
f.write("File\nHandling")
f.seek(0)
a=f.readline(-1)
print(a)
a. File Handling
b. FileHandling
c. File
d. No Output
Hide Answer
Ans. c. File

Q100. Write the output of the following:


f=open("test.txt","w+")
f.write("File\nHandling")
f.seek(0)
a=f.readline(2)
print(a)
a. File\nHandling
b. FileHandling
c. Fi
d. No Output
Hide Answer
Ans. c. Fi

You might also like