MCQ (Revision Tour, Functions and File Handling) With Solution

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

Python Question and Answers – Built-in Functions – 1

1. Which of the following functions is a built-in function in python?


a) seed() b) sqrt() c) factorial() d) print()
Answer: d
EXPLANATION: The function seed is a function which is present in the random module. The functions sqrt and factorial are a
part of the math module. The print function is a built-in function which prints a value directly to the system output.

2. What is the output of the expression:


round(4.576)
a) 4.5 b) 5 c) 4 d) 4.6
Answer: b
EXPLANATION: This is a built-in function which rounds a number to give precision in decimal digits. In the above case, since
the number of decimal places has not been specified, the decimal number is rounded off to a whole number. Hence the output
will be 5.

3. The function pow(x,y,z) is evaluated as:


a) (x**y)**z b) (x**y) / z
c) (x**y) % z d) (x**y)*z
Answer: c
EXPLANATION: The built-in function pow() can accept two or three arguments. When it takes in two arguments, they are
evaluated as: x**y. When it takes in three arguments, they are evaluated as: (x**y)%z.

4. What is the output of the


expression? round(4.5676,2)?
a) 4.5 b) 4.6 c) 4.57 d) 4.56
Answer: c
EXPLANATION: The function round is used to round off the given decimal number to the specified decimal places. In this case
the number should be rounded off to two decimal places. Hence the output will be 4.57.

5. What is the output of the following


function? any([2>8, 4>2, 1>2])
a) Error b) True c) False d) 4>2
Answer: b
EXPLANATION: The built-in function any() returns true if any or more of the elements of the iterable is true (non zero), If all
the elements are zero, it returns false.

6. What is the output of the function shown


below? import math
abs(math.sqrt(25))
a) Error b) -5 c) 5 d) 5.0
Answer: d
EXPLANATION: The abs() function prints the absolute value of the argument passed. For example: abs(-5)=5. Hence , in this
case we get abs(5.0)=5.0.

7. What are the outcomes of the functions shown


below? sum(2,4,6)
sum([1,2,3])
a) Error, 6 b) 12, Error c) 12, 6 d) Error, Error
Answer: a
EXPLANATION: The first function will result in an error because the function sum() is used to find the sum of iterable numbers.
Hence the outcomes will be Error and 6 respectively.
8. What is the output of the function:
all(3,0,4.2)
a) True b) False c) Error d) 0
Answer: c
EXPLANATION: The function all() returns ‘True’ if any one or more of the elements of the iterable are non zero. In the above
case, the values are not iterable, hence an error is thrown.

9. What is the output of the functions shown


below? min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d) -4
Answer: b
EXPLANATION: The function max() is being used to find the maximum value from among -3, -4 and false. Since false amounts
to the value zero, hence we are left with min(0, 2, 7) Hence the output is 0 (false).

Python Question and Answers – Built-in Functions – 2

1. What are the outcomes of the following


functions? chr(‘97’)
chr(97)
a) a and Erro b) ‘a’ c) Error d) Error
Error
Answer: c
EXPLANATION: The built-in function chr() returns the alphabet corresponding to the value given as an argument. This function
accepts only integer type values. In the first function, we have passed a string. Hence the first function throws an error.

2. What is the output of the following


function? complex(1+2j)
a) Error b) 1 c) 2j d) 1+2j
Answer: d
EXPLANATION: The built-in function complex() returns the argument in a complex form. Hence the output of the function
shown above will be 1+2j.

3. What is the output of the function complex() ?


a) 0j b) 0+0j c) 0 d) Error
Answer: a
EXPLANATION: The complex function returns 0j if both of the arguments are omitted, that is, if the function is in the form of
complex() or complex(0), then the output will be 0j.

4. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b) b) (a//b, a%b)
c) (a//b, a*b) c) (a/b, a%b)
Answer: b
EXPLANATION: The function divmod(a,b) is evaluated as a//b, a%b, if both ‘a’ and ‘b’ are integers.

5. What is the output of the functions shown


below? divmod(10.5,5)
divmod(2.4,1.2)
a) (2.00, 0.50) and (2.00, 0.00) b) (2, 0.5) and (2, 0)
c) (2.0, 0.5) and (2.0, 0.0) d) (2, 0.5) and (2)
Answer: c
EXPLANATION: See python documentation for the function divmod.
Python Question and Answers – Built-in Functions – 3

1. Which of the following functions accepts only integers as arguments?


a) ord() b) min() c) chr() d) any()
Answer: c
EXPLANATION: The function chr() accepts only integers as arguments. The function ord() accepts only strings. The functions
min() and max() can accept floating point as well as integer arguments.

2. Suppose there is a list such that: l=[2,3,4].


If we want to print this list in reverse order, which of the following methods should be used?
a) reverse(l) b) list(reverse[(l)])
c) reversed(l) d) list(reversed(l))
Answer: d
EXPLANATION: The built-in function reversed() can be used to reverse the elements of a list. This function accepts only an
iterable as an argument. To print the output in the form of a list, we use: list(reversed(l)). The output will be: [4,3,2].

3. What is the output of the functions shown


below? ord(65)
ord(‘A’)
a) A and 65 b) Error and 65
c) A and Error c) Error and Error
Answer: b
EXPLANATION: The built-in function ord() is used to return the ASCII value of the alphabet passed to it as an argument. Hence
the first function results in an error and the output of the second function is 65.

4. Which of the following functions will not result in an error when no arguments are passed to it?
a) min()b) divmod() c) all() d) float()
Answer: d
EXPLANATION: The built-in functions min(), max(), divmod(), ord(), any(), all() etc throw an error when no arguments are passed
to them. However there are some built-in functions like float(), complex() etc which do not throw an error when no arguments are
passed to them. The output of float() is 0.0.

5. What is the output of the function:


len(["hello",2, 4, 6])
a) 4 b) 3 c) Error d) 6
Answer: a
EXPLANATION: The function len() returns the length of the number of elements in the iterable. Therefore the output of the
function shown above is 4.

Python MCQ of – Function – 1

1. Which of the following is the use of function in python?


a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
Answer: a
EXPLANATION: Functions are reusable pieces of programs. They allow you to give a name to a block of statements, allowing
you to run that block using the specified name anywhere in your program and any number of times.

2. Which keyword is use for function?


a) Fun b) Define c) Def d) Function
Answer: c
EXPLANATION: None.

3. What is the output of the below


program? def sayHello():
print('Hello World!')
sayHello()
sayHello()
a) Hello World! and Hello World!
b) ‘Hello World!’ and ‘Hello World!’
c) Hello and Hello
d) None of the mentioned
Answer: a
EXPLANATION: Functions are defined using the def keyword. After this keyword comes an identifier name for the function,
followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next
follows the block of statements that are part of this function.
def sayHello():
print('Hello World!') # block belonging to the
function # End of function #
sayHello() # call the function
sayHello() # call the function
again

4. What is the output of the below


program? def printMax(a, b):
if a > b:
print(a, 'is
maximum') elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
a) 3 b) 4 c) 4 is maximumd) None of the mentioned
Answer: c
EXPLANATION: Here, we define a function called printMax that uses two parameters called a and b. We find out the greater
number using a simple if..else statement and then print the bigger number.

5. What is the output of the below program


? x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)
a) x is now 50 b) x is now 2
c) x is now 100 d) None of the mentioned
Answer: a
EXPLANATION: The first time that we print the value of the name x with the first line in the function’s body, Python uses the
value of the parameter declared in the main block, above the function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x
defined in the main block remains unaffected.
With the last print function call, we display the value of x as defined in the main block, thereby confirming that it is actually
unaffected by the local assignment within the previously called function.
6. What is the output of the below
program? x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
Answer: b
EXPLANATION: The global statement is used to declare that x is a global variable – hence, when we assign a value to x inside
the function, that change is reflected when we use the value of x in the main block.

7. What is the output of below


program? def say(message, times = 1):
print(message * times)
say('Hello')
say('World', 5)
a) Hello and WorldWorldWorldWorldWorld
b) Hello and World 5
c) Hello and World,World,World,World,World
d) Hello and HelloHelloHelloHelloHello
Answer: a
EXPLANATION: For some functions, you may want to make some parameters optional and use default values in case the user
does not want to provide values for them. This is done with the help of default argument values. You can specify default
argument values for parameters by appending to the parameter name in the function definition the assignment operator (=)
followed by the default value.
The function named say is used to print a string as many times as specified. If we don’t supply a value, then by default, the
string is printed just once. We achieve this by specifying a default argument value of 1 to the parameter times.
In the first usage of say, we supply only the string and it prints the string once. In the second usage of say, we supply both the
string and an argument 5 stating that we want to say the string message 5 times.

8. What is the output of the below


program? def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is',
c) func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
a) a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is
24
a is 5 and b is 100 and c is 50
b) a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is
24
a is 50 and b is 100 and c is 5
c) a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is
24
a is 100 and b is 5 and c is 50
d) None of the mentioned
Answer: c
EXPLANATION: If you have some functions with many parameters and you want to specify only some of them, then you can
give values for such parameters by naming them – this is called keyword arguments – we use the name (keyword) instead of
the position (which we have been using all along) to specify the arguments to the function.
The function named func has one parameter without a default argument value, followed by two parameters with default
argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 7 and c gets the default value of

9.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the argument. Then, the parameter
c gets the value of 24 due to naming i.e. keyword arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments for all specified values. Notice that we are specifying the
value for parameter c before that for a even though a is defined before c in the function definition.
9. What is the output of below
program? def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2 b) 3 c) The numbers are equal
d) None of the mentioned
Answer: b
EXPLANATION: The maximum function returns the maximum of the parameters, in this case the numbers supplied to the
function. It uses a simple if..else statement to find the greater value and then returns that value.

Python MCQ of – Function – 2


.
1. Which are the advantages of functions in python?
a) Reducing duplication of code
b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code
d) All of the mentioned
Answer: d
EXPLANATION: None.

2. What are the two main types of functions?


a) Custom function
b) Built-in function & User defined function
c) User function d) System function
Answer: b
EXPLANATION: Built-in functions and user defined ones. The built-in functions are part of the Python language. Examples are:
dir(), len() or abs(). The user defined functions are functions created with the def keyword.

3. Where is function defined?


a) Module b) Class
c) Another function d) All of the mentioned
Answer: d
EXPLANATION: Functions can be defined inside a module, a class or another function.

4. What is called when a function is defined inside a class?


a) Module b) Class
c) Another function d) Method
Answer: d
EXPLANATION: None.

5. Which of the following is the use of id() function in python?


a) Id returns the identity of the object
b) Every object doesn’t have a unique id
c) All of the mentioned
d) None of the mentioned
Answer: a
EXPLANATION: Each object in Python has a unique id. The id() function returns the object’s id.

6. Which of the following refers to mathematical function?


a) sqrt b) rhombus c) add d) rhombus
Answer: a
EXPLANATION: Functions that are always available for usage, functions that are contained within external modules, which
must be imported and functions defined by a programmer with the def keyword.
Eg: math import sqrt
A sqrt() function is imported from the math module.

7. What is the output of below


program? def cube(x):
return x * x *
x x = cube(3)
print x

a) 9b) 3 c) 27 d) 30
Answer: c
EXPLANATION: A function is created to do a specific task. Often there is a result from such a task. The return keyword is used
to return values from a function. A function may or may not return a value. If a function does not have a return keyword, it will
send a none value.

8. What is the output of the below


program? def C2F(c):
return c * 9/5 + 32
print C2F(100)
print C2F(0)
a) 212 and 32 b) 314 and 24
c) 567 and 98 d) None of the mentioned
Answer: a
EXPLANATION: The code shown above is used to convert a temperature in degree celsius to fahrenheit.

9. What is the output of the below


program? def power(x, y=2):
r=1
for i in range(y):
r=r*x
return r
print power(3)
print power(3, 3)
a) 212 and 32 b) 9 and 27
c) 567 and 98 d) None of the mentioned
Answer: b
EXPLANATION: The arguments in Python functions may have implicit values. An implicit value is used, if no value is
provided. Here we created a power function. The function has one argument with an implicit value. We can call the function
with one or two arguments.

10. What is the output of the below


program? def sum(*args):
'''Function returns the sum
of all values'''
r=0
for i in args:
r += i
return r
print sum. doc
print sum(1, 2, 3)
print sum(1, 2, 3, 4, 5)
a) 6 and 15 b) 6 and 100
c) 123 and 12345 d) None of the mentioned
Answer: a
EXPLANATION: We use the * operator to indicate, that the function will accept arbitrary number of arguments. The sum()
function will return the sum of all arguments. The first string in the function body is called the function documentation string.
It is used to document the function. The string must be in triple quotes.

Python MCQ of – Function – 3

1. What is a variable defined outside a function referred to


as? a)A static variable b)A global variable
c)A local variable d)An automatic variable
Answer: b
EXPLANATION: The value of a variable defined outside all function definitions is referred to as a global variable and can be
used by multiple functions of the program.

2.What is a variable defined inside a function referred to


as? a)A global variable b)A volatile variable
c)A local variable d)An automatic variable
Answer: c
EXPLANATION: The variable inside a function is called as local variable and the variable definition is confined only to that
function.

3.What is the output of the following


code? i=0
def change(i):
i=i+1
return i
change(1)
print(i)
a)1
b) Nothing is displayed
c) 0 d)An exception is thrown
Answer: c
EXPLANATION: Any change made in to an immutable data type in a function isn’t reflected outside the function.

4. What is the output of the following piece of


code? def a(b):
b = b + [5]
c = [1, 2, 3, 4]
a(c)
print(len(c))
a)4 b)5 c)1 d)An exception is thrown
Answer: b
EXPLANATION: Since a list is mutable, any change made in the list in the function is reflected outside the function.

5.What is the output of the following


code? a=10
b=20
def change():
global b
a=45
b=56
change()
print(a)
print(b)
a)10 and 56 b)45 and 56
c)10 and 20 d)Syntax Error
Answer: a
EXPLANATION: The statement “global b” allows the global value of b to be accessed and changed. Whereas the variable a is
local and hence the change isn’t reflected outside the function.

6. What is the output of the following


code? def change(i = 1, j = 2):
i=i+j
j=j+1
print(i, j)
change(j = 1, i = 2)
a)An exception is thrown because of conflicting values
b)1 2 c)3 3 d)3 2
Answer: d
EXPLANATION: The values given during function call is taken into consideration, that is, i=2 and j=1.

7.What is the output of the following


code? def change(one, *two):
print(type(two))
change(1,2,3,4)
a)Integer b)Tuple
c) Dictionary d)An exception is thrown
Answer: b
EXPLANATION: The parameter two is a variable parameter and consists of (2,3,4). Hence the data type is tuple.

8. If a function doesn’t have a return statement, which of the following does the function
return? a)int b)null c)None
d) An exception is thrown without the return statement
Answer: c
EXPLANATION: A function can exist without a return statement and returns None if the function doesn’t have a return statement.
9. What is the output of the following
code? def display(b, n):
while n > 0:
print(b,end="")
n=n-1
display('z',3)
a)zzz b)zz c)An exception is executed d)Infinite loop
Answer: a
EXPLANATION: The loop runs three times and ‘z’ is printed each time.

10. What is the output of the following piece of


code? def find(a, **b):
print(type(b))
find('letters',A='1',B='2')
a)String b)Tuple
c)Dictionary d)An exception is thrown
Answer: c
EXPLANATION: b combines the remaining parameters into a dictionary.

Python MCQ of – Argument Parsing 1


1. What is the type of each element in sys.argv?
a) set b) list c) tuple d) string
Answer: d
EXPLANATION: It is a list of strings.

2. What is the length of sys.argv?


a) number of arguments b) number of arguments + 1
c) number of arguments – 1 d) none of the mentioned
Answer: b
EXPLANATION: The first argument is the name of the program itself. Therefore the length of sys.argv is one more than the
number arguments.

3. What is the output of the following


code? def foo(k):
k[0] = 1
q = [0]
foo(q)
print(q)
a) [0]. ) [1]. c) [1, 0]. d) [0, 1].
Answer: b
EXPLANATION: Lists are passed by reference.

4. How are keyword arguments specified in the function heading?


a) one star followed by a valid identifier
b) one underscore followed by a valid identifier
c) two stars followed by a valid identifier
d) two underscores followed by a valid identifier
Answer: c
EXPLANATION: Refer documentation.

5. How many keyword arguments can be passed to a function in a single function call?
a) zero b) one c) zero or more d) one or more
Answer: c
EXPLANATION: zero keyword arguments may be passed if all the arguments have default values.

6. What is the output of the following


code? def foo(fname, val):
print(fname(val))
foo(max, [1, 2, 3])
foo(min, [1, 2, 3])
a) 3 1 b) 1 3 c) error d) none of the mentioned
Answer: a
EXPLANATION: It is possible to pass function names as arguments to other functions.

7. What is the output of the following


code? def foo():
return total + 1
total = 0
print(foo())
a) 0 b) 1 c) error d) none of the mentioned
Answer: b
EXPLANATION: It is possible to read the value of a global variable directly.

8. What is the output of the following


code? def foo():
total += 1
return total
total = 0
print(foo())
a) 0 b) 1 c) error d) none of the mentioned
Answer: c
EXPLANATION: It is not possible to change the value of a global variable without explicitly specifying it.

9. What is the output of the following


code? def foo(x):
x = ['def',
'abc'] return
id(x)
q = ['abc', 'def']
print(id(q) ==
foo(q))
a) True b) False c) None d) Error
Answer: b
EXPLANATION: A new object is created in the function.

10. What is the output of the following


code? def foo(i, x=[]):
x.append(i)
return x
for i in range(3):
print(foo(i))
a) [0] [1] [2] b) [0] [0, 1] [0, 1, 2].
c) [1] [2] [3]. d) [1] [1, 2] [1, 2, 3].
Answer: b
EXPLANATION: When a list is a default value, the same list will be reused.

Python MCQ of – Argument Parsing 2


1. What is the output of the following
code? def foo(k):
k = [1]
q = [0]
foo(q)
print(q)
a) [0]. b) [1]. c) [1, 0]. d) [0, 1].
Answer: a
EXPLANATION: A new list object is created in the function and the reference is lost. This can be checked by comparing the id
of k before and after k = [1].

2. How are variable length arguments specified in the function heading?


a) one star followed by a valid identifier
b) one underscore followed by a valid identifier
c) two stars followed by a valid identifier
d) two underscores followed by a valid identifier
Answer: a
EXPLANATION: Refer documentation.

3. Which module in the python standard library parses options received from the command line?
a) getopt b) os c) getarg d) main
Answer: a
EXPLANATION: getopt parses options received from the command line.

4. What is the type of sys.argv?


a) set b) list c) tuple d) string
Answer: b
EXPLANATION: It is a list of elements.

5. What is the value stored in sys.argv[0]?


a) null
b) you cannot access it
c) the program’s name
d) the first argument
Answer: c
EXPLANATION: Refer documentation.

6. How are default arguments specified in the function heading?


a) identifier followed by an equal to sign and the default value
b) identifier followed by the default value within backticks (“)
c) identifier followed by the default value within square brackets ([])
d) identifier
Answer: a
EXPLANATION: Refer documentation.

7. How are required arguments specified in the function heading?


a) identifier followed by an equal to sign and the default value
b) identifier followed by the default value within backticks (“)
c) identifier followed by the default value within square brackets ([])
d) identifier
Answer: d
EXPLANATION: Refer documentation.
8. What is the output of the following
code? def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) ==
foo(q))
a) True b) False c) None d) Error
Answer: a
EXPLANATION: The same object is modified in the function.

9. Where are the arguments received from the command line stored?
a) sys.argv b) os.argv
c) argv d) none of the mentioned
Answer: a
EXPLANATION: Refer documentation.

10. What is the output of the


following? def foo(i, x=[]):
x.append(x.append(i))
return x
for i in range(3):
y = foo(i)
print(y)
a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]].
b) [[0], [[0], 1], [[0], [[0], 1], 2]].
c) [0, None, 1, None, 2, None].
d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]].
Answer: c
EXPLANATION: append() returns None.

Python MCQ of – Global vs Local Variables – 1


1. The output of the code shown below is:
def f1():
x=15
print(x)
x=12
f1()
a) Error b) 12 c) 15 d) 1512
Answer: c
EXPLANATION: In the code shown above, x=15 is a local variable whereas x=12 is a global variable. Preference is given to
local variable over global variable. Hence the output of the code shown above is 15.

2. What is the output of the code shown


below? def f1():
x=100
print(x)
x=+1
f1()
a) Error b) 100 c) 101 d) 99
Answer: b
EXPLANATION: The variable x is a local variable. It is first printed and then modified. Hence the output of this code is 100.
3. What is the output of the code shown
below? def san(x):
print(x+1)
x=-2
x=4
san(12)
a) 13 b) 10 c) 2 d) 5
Answer: a
EXPLANATION: The value passed to the function san() is 12. This value is incremented by one and printed. Hence the output
of the code shown above is 13.

4. What is the output of the code


shown? def f1():
global x
x+=1
print(x)
x=12
print("x")
a) Error b) 13 c) 13 d) x
Answer: d
EXPLANATION: In the code shown above, the variable ‘x’ is declared as global within the function. Hence the output is ‘x’.
Had the variable ‘x’ been a local variable, the output would have been:
13

5. What is the output of the code shown


below? def f1(x):
global x
x+=1
print(x)
f1(15)
print("hello")
a) error b) hello c) 16 d) 16

hello
Answer: a
EXPLANATION: The code shown above will result in an error because ‘x’ is a global variable. Had it been a local variable, the
output would be: 16
hello

6. What is the output of the following


code? x=12
def f1(a,b=x):
print(a,b)
x=15
f1(4)
a) Error b) 12 4 c) 4 12 d) 4 15
Answer: c
EXPLANATION: At the time of leader processing, the value of ‘x’ is 12. It is not modified later. The value passed to the
function f1 is 4. Hence the output of the code shown above is 4 12.

7. What is the output of the code


shown? def f():
global a
print(a)
a = "hello"
print(a)
a = "world"
f()
print(a)
a) helloandhelloandworld
b) world andworldandhello
c) hello andworldandworld
d) world andhelloandworld
Answer: b
EXPLANATION: Since the variable ‘a’ has been explicitly specified as a global variable, the value of a passed to the function is
‘world’. Hence the output of this code is: world
world
hello

8. What is the output of the code shown


below? def f1(a,b=[]):
b.append(a)
return b
print(f1(2,[3,4]))
a) [3,2,4] b) [2,3,4] c) Error d) [3,4,2]
Answer: d
EXPLANATION: In the code shown above, the integer 2 is appended to the list [3,4]. Hence the output of the code is [3,4,2].
Both the variables a and b are local variables.

9. What is the output of the code shown


below? def f(p, q, r):
global s
p = 10
q = 20
r = 30
s = 40
print(p,q,r,s)

p,q,r,s = 1,2,3,4
f(5,10,15)
a) 1 2 3 4 b) 5 10 15 4
c) 10 20 30 40 d) 5 10 15 40
Answer: c
EXPLANATION: The above code shows a combination of local and global variables. The output of this code is: 10 20 30 40

10. What is the output of the code shown


below? def f(x):
print("outer")
def f1(a):
print("inner")
print(a,x)
f(3)
f1(1)
a) outer and error
b) inner and error
c) outer and inner
d) error
Answer: a
EXPLANATION: The error will be caused due to the statement f1(1) because the function is nested. If f1(1) had been called
inside the function, the output would have been different and there would be no error.

11. The output of code shown below is:


x=5
def f1():
global x
x=4
def f2(a,b):
global x
return a+b+x
f1()
total = f2(1,2)
print(total)
a) Error b) 7 c) 8 d) 15
Answer: b
EXPLANATION: In the code shown above, the variable ‘x’ has been declared as a global variable under both the functions f1
and f2. The value returned is a+b+x = 1+2+4 = 7.

12. What is the output of the code shown


below? x=100
def f1():
global x
x=90
def f2():
global x
x=80
print(x)
a) 100 b) 90 c) 80 d) Error
Answer: a
EXPLANATION: The output of the code shown above is 100. This is because the variable ‘x’ has been declared as global within
the functions f1 and f2.

13. Read the code shown below carefully and point out the global variables:

y, z = 1, 2
def f():
global x
x = y+z
a) x b) y and z
c) x, y and z d) Neither x, nor y, nor z
Answer: c
EXPLANATION: In the code shown above, x, y and z are global variables inside the function f. y and z are global because they
are not assigned in the function. x is a global variable because it is explicitly specified so in the code. Hence, x, y and z are
global variables.

Python MCQ of – Global vs Local Variables – 2


1. Which of the following data structures is returned by the functions globals() and locals()?
a) list b) set c) dictionary d) tuple
Answer: c
EXPLANATION: Both the functions, that is, globals() and locals() return value of the data structure dictionary.

2. What is the output of the code shown


below? x=1
def cg():
global x
x=x+1
cg()
a) 2 b) 1 c) 0 d) Error
Answer: a
EXPLANATION: Since ‘x’ has been declared a global variable, it can be modified very easily within the function. Hence the
output is 2.

3. On assigning a value to a variable inside a function, it automatically becomes a global variable. State whether true or false.
a) True b) False
Answer: b
EXPLANATION: On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above
statement is false.

4. What is the output of the code shown


below? e="butter"
def f(a): print(a)+e
f("bitter")
a) error b) butter error c) bitter
error
d) bitterbutter
Answer: c
EXPLANATION: The output of the code shown above will be ‘bitter’, followed by an error. The error is because the operand
‘+’ is unsupported on the types used above.

5. What happens if a local variable exists with the same name as the global variable you want to access?
a) Error b) The local variable is shadowed
c) Undefined behavior d) The global variable is shadowed
Answer: d
EXPLANATION: If a local variable exists with the same name as the local variable that you want to access, then the global
variable is shadowed. That is, preference is given to the local variable.

6. What is the output of the code shown


below? a=10
globals()['a']=25
print(a)
a) 10 b) 25 c) Junk value d) Error
Answer: b
EXPLANATION: In the code shown above, the value of ‘a’ can be changed by using globals() function. The dictionary returned
is accessed using key of the variable ‘a’ and modified to 25.

7. What is the output of this


code? def f(): x=4
x=1
f()

a) Error b) 4 c) Junk value d) 1


Answer: d
EXPLANATION: In the code shown above, when we call the function f, a new namespace is created. The assignment x=4 is
performed in the local namespace and does not affect the global namespace. Hence the output is 1.

8. returns a dictionary of the module namespace.


returns a dictionary of the current namespace.
a) locals() and globals() b) locals() and locals()
c) globals() and locals()d) globals() and globals()
Answer: c
EXPLANATION: The function globals() returns a dictionary of the module namespace, whereas the function locals() returns a
dictionary of the current namespace.

Python MCQ of – Python Modules

1. Which of these definitions correctly describes a module?


a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code
Answer: b
EXPLANATION: The term “module” refers to the implementation of specific functionality to be incorporated into a program.

2. Which of the following is not an advantage of using


modules? a)Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
Answer: c
EXPLANATION: The total size of the program remains the same regardless of whether modules are used or not. Modules simply
divide the program.

3. Which of the following is false about “import modulename” form of


import? a)The namespace of imported module becomes part of importing
module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier
Answer: a
EXPLANATION: In the “import modulename” form of import, the namespace of imported module becomes available to, but
not part of, the importing module.

4. Which of the following is false about “from-import” form of


import? a)The syntax is: from modulename import identifier
b) This form of import prevents name clash
c) The namespace of imported module becomes part of importing module
d) The identifiers in module are accessed directly as: identifier
Answer: b
EXPLANATION: In the “from-import” form of import, there may be name clashes because names of the imported identifiers
aren’t specified along with the module name.

5. What is the output of the following piece of


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))
Answer: d
EXPLANATION: In the “from-import” form of import, the imported identifiers (in this case factorial()) aren’t specified along
with the module name.

Python MCQ of – Math Module – 1

1. What is returned by
math.ceil(3.4)? a) 3 b) 4 c) 4.0
d) 3.0 Answer: b
EXPLANATION: The ceil function returns the smallest integer that is bigger than or equal to the number itself.

2. What is the value returned by


math.floor(3.4)? a) 3 b) 4 c) 4.0 d) 3.0
Answer: a
EXPLANATION: The floor function returns the biggest number that is smaller than or equal to the number itself.

3. What is displayed on executing print(math.fabs(-


3.4))? a) -3.4 b) 3.4 c) 3 d) -3
Answer: b
EXPLANATION: A negative floating point number is returned as a positive floating point number.

4. Is the output of the function abs() the same as that of the function math.fabs()?
a) sometimes b) always
c) never d) none of the mentioned
Answer: a
EXPLANATION: math.fabs() always returns a float and does not work with complex numbers whereas the return type of abs() is
determined by the type of value that is passed to it.

5. What is the value returned by


math.fact(6)? a) 720 b) 6 c) [1, 2, 3,
6]. d) error Answer: d
EXPLANATION: NameError, fact() is not defined.

6. What is the value of x if x = math.factorial(0)?


a) 0 b) 1 c) error d) none of the mentioned
Answer: b
EXPLANATION: Factorial of 0 is 1.

7. What is math.factorial(4.0)?
a) 24 b) 1 c) error d) none of the mentioned
Answer: a
EXPLANATION: The factorial of 4 is returned.

8. What is the output of


print(math.factorial(4.5))? a) 24 b) 120 c)
error d) 24.0
Answer: c
EXPLANATION: Factorial is only defined for non-negative integers.

9. What is
math.floor(0o10)? a) 8 b) 10
c) 0 d) 9 Answer: a
EXPLANATION: 0o10 is 8 and floor(8) is 8.
Python MCQ of – Math Module – 2

1. What is the result of


math.trunc(3.1)? a) 3.0 b) 3 c) 0.1
d) 1
Answer: b
EXPLANATION: The integral part of the floating point number is returned.

2. What is the output of print(math.trunc(‘3.1’))?


a) 3 b) 3.0 c) error d) none of the mentioned
Answer: c
EXPLANATION: TypeError, a string does not have trunc method.

3. What is the default base used when math.log(x) is found?


a) e b) 10 c) 2 d) none of the mentioned
Answer: a
EXPLANATION: The natural log of x is returned by default.

4. Which of the following aren’t defined in the math module?


a) log2() b) log10()
c) logx() d) none of the mentioned
Answer: c
EXPLANATION: log2() and log10() are defined in the math module.

5. What is returned by int(math.pow(3, 2))?


a) 6 b) 9
c) error, third argument required
d) error, too many arguments
Answer: b
EXPLANATION: math.pow(a, b) returns a ** b.

6. What is output of print(math.pow(3, 2))?


a) 9 b) 9.0 c) None d) none of the mentioned
Answer: b
EXPLANATION: math.pow() returns a floating point number.

7. What is the value of x if x = math.sqrt(4)?


a) 2 b) 2.0 c) (2, -2) d) (2.0, -2.0)
Answer: b
EXPLANATION: The function returns one floating point number.

8. What does math.sqrt(X, Y) do?


a) calculate the Xth root of Y
b) calculate the Yth root of X
c) error
d) return a tuple with the square root of X and Y
Answer: c
EXPLANATION: The function takes only one argument.
Python Question and Answers – Random module – 1

1. To include the use of functions which are present in the random library, we must use the option:
a) import random b) random.h
c) import.random d) random.random
Answer: a
EXPLANATION: The command import random is used to import the random module, which enables us to use the functions
which are present in the random library.

2. The output of the following snippet of code is either 1 or 2. State whether this statement is true or
false. import random
random.randint(1,2)
a) True
b) False
Answer: a
EXPLANATION: The function random.randint(a,b) helps us to generate an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’. In
this case, since there are no integers between 1 and 2 , the output will necessarily be either 1 or 2’.

3. What is the interval of the value generated by the function random.random(), assuming that the random module has already
been imported?
a) (0,1) b) (0,1] c) [0,1] d) [0,1)
Answer: d
EXPLANATION: The function random.random() generates a random value in the interval [0,1), that is, including zero but
excluding one.

4. Which of the following is a possible outcome of the function shown


below? random.randrange(0,91,5)
a) 10 b) 18 c) 79 d) 95
Answer: a
EXPLANATION: The function shown above will generate an output which is a multiple of 5 and is between 0 and 91. The only
option which satisfies these criteria is 10. Hence the only possible output of this function is 10.

5. Both the functions randint and uniform accept parameters.


a) 0 b) 1 c) 3 d) 2
Answer: c
EXPLANATION: Both of these functions, that is, randint and uniform are included in the random module and both of these
functions accept 3 parameters. For example: random.uniform(self,a,b) where ‘a’ and ‘b’ specify the range and self is an
imaginary parameter.

6. The randrange function returns only an integer value. State whether true or false.
a) True
b) False
Answer: a
EXPLANATION: The function randrange returns only an integer value. Hence this statement is true.

7. Which of the following options is the possible outcome of the function shown
below? random.randrange(1,100,10)
a) 32 b) 67 c) 91 d) 80
Answer: c
EXPLANATION: The output of this function can be any value which is a multiple of 10, plus 1. Hence a value like 11, 21, 31,
41…91 can be the output. Also, the value should necessarily be between 1 and 100. The only option which satisfies this criteria
is 91.
Python MCQ of – Random Module – 2
1. The function random.randint(4) can return only one of the following values. Which?
a) b) 3.4 c) error d) 5
Answer: c
EXPLANATION: Error, the function takes two arguments.

2. Which of the following is equivalent to random.randint(3, 6)?


a) random.choice([3, 6]) b) random.randrange(3, 6)
c) 3 + random.randrange(3) d) 3 + random.randrange(4)
Answer: d
EXPLANATION: random.randint(3, 6) can return any one of 3, 4, 5 and 6.

3. Which of the following will not be returned by random.choice(“1 ,”)?


a) 1 b) (space) c) , d) none of the mentioned
Answer: d
EXPLANATION: Any of the characters present in the string may be returned.

4. 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)


Answer: d
EXPLANATION: Any number that is greater than or equal to 0.0 and lesser than 1.0 can be returned.

EXPLANATION: The function getcwd() (get current working directory) returns a string that represents the present working
directory.

1. What does os.link() do?


a) create a symbolic link b) create a hard link
c) create a soft link d) none of the mentioned
Answer: b
EXPLANATION: os.link(source, destination) will create a hard link from source to destination.

2. Which of the following can be used to create a directory?


a) os.mkdir() b) os.creat_dir()
c) os.create_dir() d) os.make_dir()
Answer: a
EXPLANATION: The function mkdir() creates a directory in the path specified.

3. Which of the following can be used to create a symbolic link?


a) os.symlink() b) os.symb_link()
c) os.symblin() d) os.ln()
Answer: a
EXPLANATION: It is the function that allows you to create a symbolic link.
Python MCQ of – Files – 1

1. To open a file c:\scores.txt for reading, we use


a) infile = open(“c:\scores.txt”, “r”)
b) infile = open(“c:\\scores.txt”, “r”)
c) infile = open(file = “c:\scores.txt”, “r”)
d) infile = open(file = “c:\\scores.txt”, “r”)
Answer: b
EXPLANATION: Execute help(open) to get more details.

2. To open a file c:\scores.txt for writing, we use


a) outfile = open(“c:\scores.txt”, “w”)
b) outfile = open(“c:\\scores.txt”, “w”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)
Answer: b
EXPLANATION: w is used to indicate that file is to be written to.

3. To open a file c:\scores.txt for appending data, we use


a) outfile = open(“c:\\scores.txt”, “a”)
b) outfile = open(“c:\\scores.txt”, “rw”)
c) outfile = open(file = “c:\scores.txt”, “w”)
d) outfile = open(file = “c:\\scores.txt”, “w”)
Answer: a
EXPLANATION: a is used to indicate that data is to be appended.

4. Which of the following statements are true?


a) When you open a file for reading, if the file does not exist, an error occurs
b) When you open a file for writing, if the file does not exist, a new file is created
c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file
d) All of the mentioned
Answer: d
EXPLANATION: The program will throw an error.

5. To read two characters from a file object infile, we use


a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: a
EXPLANATION: Execute in the shell to verify.

6. To read the entire remaining contents of the file as a string from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: b
EXPLANATION: read function is used to read all the lines in a file.

7. What is the
output? f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)
a) True b) False c) None d) Error
Answer: a
EXPLANATION: The WITH statement when used with open file guarantees that the file object is closed when the with block
exits.

8. To read the next line of the file from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: c
EXPLANATION: Execute in the shell to verify.

9. To read the remaining lines of the file from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: d
EXPLANATION: Execute in the shell to verify.

10. The readlines() method returns


a) str b) a list of lines
c) a list of single characters d) a list of integers
Answer: b
EXPLANATION: Every line is stored in a list and returned.

Python MCQ of – Files – 2

1. What is the use of tell() method in python?


a) tells you the current position within the file
b) tells you the end position within the file
c) tells you the file is opened or not
d) none of the mentioned

Answer: a
EXPLANATION: The tell() method tells you the current position within the file; in other words, the next read or write will occur
at that many bytes from the beginning of the file.

2. What is the current syntax of rename() a file?


a) rename(current_file_name, new_file_name)
b) rename(new_file_name, current_file_name,)
c) rename(()(current_file_name, new_file_name))
d) none of the mentioned
Answer: a
EXPLANATION: This is the correct syntax which has shown below.
rename(current_file_name, new_file_name)

3. What is the current syntax of remove() a file?


a) remove(file_name)
b) remove(new_file_name, current_file_name,)
c) remove(() , file_name))
d) none of the mentioned
Answer: a
EXPLANATION: remove(file_name)

4. What is the output of this


program? fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5
lines # This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):
line = fo.next()
print "Line No %d - %s" % (index,
line) # Close opened file
fo.close()
a) Compilation Error b) Syntax Error
c) Displays Output d) None of the mentioned
Answer: c
EXPLANATION: It displays the output as shown below. The method next() is used when a file is used as an iterator, typically in
a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.
Output:
Name of the file: foo.txt
Line No 0 – This is 1st line
Line No 1 – This is 2nd line
Line No 2 – This is 3rd line
Line No 3 – This is 4th line
Line No 4 – This is 5th line

5. What is the use of seek() method in files?


a) sets the file’s current position at the offset
b) sets the file’s previous position at the offset
c) sets the file’s current position within the file
d) none of the mentioned
Answer: a

EXPLANATION: Sets the file’s current position at the offset. The method seek() sets the file’s current position at the offset.
Following is the syntax for seek() method:
fileObject.seek(offset[, whence])
Parameters
offset — This is the position of the read/write pointer within the file.
whence — This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek
relative to the current position and 2 means seek relative to the file’s end.

Python MCQ of – Files – 3

Python MCQ of – Files – 4

1. In file handling, what does this terms means “r, a”?


a) read, append b) append, read
c) all of the mentioned d) none of the the mentioned
Answer: a
EXPLANATION: r- reading, a-appending.

2. What is the use of “w” in file handling?


a) Read b) Write c) Append d) None of the the mentioned
Answer: b
EXPLANATION: This opens the file for writing. It will create the file if it doesn’t exist, and if it does, it will overwrite it.
fh = open(“filename_here”, “w”).

3. What is the use of “a” in file handling?


a) Read b) Write
c) Append d) None of the the mentioned
Answer: c
EXPLANATION: This opens the fhe file in appending mode. That means, it will be open for writing and everything will be
written to the end of the file.
fh =open(“filename_here”, “a”).

4. Which function is used to read all the characters?


a) Read() b) Readcharacters()
c) Readall() d) Readchar()
Answer: a
EXPLANATION: The read function reads all characters fh = open(“filename”, “r”)
content = fh.read().

5. Which function is used to read single line from file?


a) Readline() b) Readlines()
c) Readstatement() d) Readfullline()
Answer: b
EXPLANATION: The readline function reads a single line from the file fh = open(“filename”, “r”)
content = fh.readline().

6. Which function is used to write all the characters?


a) write() b) writecharacters()
c) writeall() d) writechar()
Answer: a
EXPLANATION: To write a fixed sequence of characters to a file
fh = open(“hello.txt”,”w”)
write(“Hello World”).

7. Which function is used to write a list of string in a file


a) writeline() b) writelines()
c) writestatement() d) writefullline()
Answer: a
EXPLANATION: With the writeline function you can write a list of strings to a file
fh = open(“hello.txt”, “w”)
lines_of_text = [“a line of text”, “another line of text”, “a third line”] fh.writelines(lines_of_text).

8. Which function is used to close a file in python?


a) Close() b) Stop()
c) End() d) Closefile()
Answer: a
EXPLANATION: f.close()to close it and free up any system resources taken up by the open file.

9. Is it possible to create a text file in python?


a) Yes b) No
c) Machine dependent d) All of the mentioned
Answer: a
EXPLANATION: Yes we can create a file in python. Creation of file is as shown below.
file = open(“newfile.txt”, “w”)
file.write(“hello world in the new file\
n”) file.write(“and another line\n”)
file.close().

10. Which of the following is modes of both writing and reading in binary format in file.?
a) wb+ b) w
c) wb d) w+
Answer: a
EXPLANATION: Here is the description below
“w” Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
“wb” Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
“w+” Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
“wb+” Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does
not exist, creates a new file for reading and writing.

Python MCQ of – Files – 5

1. Which of the following is not a valid mode to open a file?


a) ab b) rw c) r+ d) w+
Answer: b
EXPLANATION: Use r+, w+ or a+ to perform both read and write operations using a single file object.

2. What is the difference between r+ and w+ modes?


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
Answer: b
EXPLANATION: none.

3. How do you get the name of a file from a file object (fp)?
a) fp.name b) fp.file(name)
c) self. name (fp) d) fp. name ()
Answer: a
EXPLANATION: name is an attribute of the file object.

4. Which of the following is not a valid attribute of a file object (fp)?


a) fp.name b) fp.closed c) fp.mode d) fp.size
Answer: d
EXPLANATION: fp.size has not been implemented.

5. How do you close a file object (fp)?


a) close(fp) b) fclose(fp)
c) fp.close() d) fp. close ()
Answer: c
EXPLANATION: close() is a method of the file object.
6. How do you get the current position within the file?
a) fp.seek() b) fp.tell() c) fp.loc d) fp.pos
Answer: b
EXPLANATION: It gives the current position as an offset from the start of file.

7. How do you rename a file?


a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)
Answer: b
EXPLANATION: os.rename() is used to rename files.

8. How do you delete a file?


a) del(fp) b) fp.delete()
c) os.remove(‘file’) d) os.delete(‘file’)
Answer: c
EXPLANATION: os.remove() is used to delete files.

9. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0) b) fp.seek(offset, 1)
c) fp.seek(offset, 2) d) none of the mentioned
Answer: a
EXPLANATION: 0 indicates that the offset is with respect to the start.

10. What happens if no arguments are passed to the seek function?


a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error
Answer: d
EXPLANATION: seek() takes at least one argument.

Python MCQ of – Exception Handling – 1

1. How many except statements can a try-except block have?


a) zero b) one c) more than one d) more than zero
Answer: d
EXPLANATION: There has to be at least one except statement.
2. When will the else part of try-except-else be executed?
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block
Answer: c
EXPLANATION: The else part is executed when no exception occurs.
3. Is the following code valid? try:
# Do something except:
# Do something finally:
# Do something
a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes
Answer: b
EXPLANATION: Refer documentation.
4. Is the following code valid? try:
# Do something except:
# Do something else:
# Do something
a) no, there is no such thing as else
b) no, else cannot be used with except
c) no, else must come before except
d) yes
Answer: d
EXPLANATION: Refer documentation.
5. Can one block of except statements handle multiple exception?
a) yes, like except TypeError, SyntaxError [,…].
b) yes, like except [TypeError, SyntaxError].
c) no
d) none of the mentioned
Answer: a
EXPLANATION: Each type of exception can be specified directly. There is no need to put it in a list.
6. When is the finally block executed?
a) when there is no exception
b) when there is an exception

c) only if some condition that has been specified is satisfied


d) always
Answer: d
EXPLANATION: The finally block is always executed.
7. What is the output of the following code? def foo():
try:
return 1 finally:
return 2 k = foo() print(k)
a) 1 b) 2 c) 3
d) error, there is more than one return statement in a single try-finally block
Answer: b
EXPLANATION: The finally block is executed even there is a return statement in the try block.

8. What is the output of the following code? def foo():


try:
print(1) finally:
print(2)
foo()
a) 1 2 b) 1 c) 2 d) none of the mentioned
Answer: a
EXPLANATION: No error occurs in the try block so 1 is printed. Then the finally block is executed and 2 is printed.
9. What is the output of the following? try:
if '1' != 1:
raise
"someError" else:
print("someError has not occurred") except "someError":
print ("someError has occurred")
a) someError has occurred
b) someError has not occurred
c) invalid code
d) none of the mentioned
Answer: c
EXPLANATION: A new exception class must inherit from a BaseException. There is no such inheritance here.
10. What happens when ‘1’ == 1 is executed?
a) we get a True
b) we get a False
c) an TypeError occurs
d) a ValueError occurs
Answer: b
EXPLANATION: It simply evaluates to False and does not raise any exception.

1 MARKS QUESTIONS
1. Which of the following is valid arithmetic operator in Python:
(i) // (ii) ? (iii) <(iv) and
Answer (i) //
2. Write the type of tokens from the following:
(i) if (ii) roll_no
Answer (i) Key word (ii) Identifier
(1/2 mark for each correct type)
3. Name the Python Library modules which need to be imported toinvoke
the
following functions:
(i) sin( ) (ii) randint ( )
Answer (i) math (ii) random
(1/2 mark for each module)
4 What do you understand by the term Iteration?
Answer Repeatation of statement/s finite number of times is known asIteration.
(1 mark for correct answer)

5 Which is the correct form of declaration of dictionary?


(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Answer (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
6 Identify the valid declaration of L:
L = [1, 23, ‘hi’, 6].
(i) list (ii) dictionary (iii) array (iv) tuple
Answer (i) List
7 Find and write the output of the following python code:x =
"abcdef"
i = "a" while i
in x:
print(i, end = " ")
Answer aaaaaa----- OR infinite loop
8 Find and write the output of the following python code:
a=10
def call():
global a
a=15 b=20
print(a)
call()

Answer 15
9 Find the valid identifier from the following

a) My-Name b) True c) 2ndName d) S_name

Answer s) S_name
Given the lists L=[1,3,6,82,5,7,11,92] , What will be the output of
print(L[2:5])
Answer [6,82,5]

11 Write the full form of IDLE.

Answer Integrated Development Learning Environment

12 Identify the valid logical operator in Python from the following. 1

a) ? b) < c) ** d) and

Answer d) and

13 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80), 1


which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))
Answer b) Tup[2]=90

14 Write a statement in Python to declare a dictionary whose keys are 1


1,2,3 and values are Apple, Mango and Banana respectively.

Answer Dict={1:’Apple’, 2: ’Mango’,3 : ‘Banana’}


15 A tuple is declared as T = (2,5,6,9,8)
What will be the value of sum(T)?
Answer 30

16 Name the built-in mathematical function / method that is used to


return square root of a number.

Answer sqrt()

17 If the following code is executed, what will be the output of the


following code? str="KendriyaVidyalayaSangathan"

print(str[8:16])

Answer Vidyalay

18 Which of the following are valid operators in Python:

(i) ** (ii) between (iii) like (iv) ||

Answer a) (I) and (iv)

19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of
print(L[3:4])
Answer [“N”]
20 What will be the output of: 1
print(10>20)
Answer False
2 MARKS QUESTIONS
1. Rewrite the following code in python after removing all syntax 2
error(s). Underline each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
Answer To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)
(1/2 mark for each correction)
2. Find and write the output of the following python code: 2
def fun(s):
k=len(s)
m=" "
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+'bb'
print(m)
fun('school2@com')
Answer SCHOOLbbbbCOM
(2 marks for correct output)
Note: Partial marking can also be given
3. What possible outputs(s) are expected to be displayed on screen at 2
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 FROM and TO.
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=”# “)

(i) 10#40#70# (ii) 30#40#50#


(iii) 50#60#70# (iv) 40#50#70#
Answer (ii) 30#40#50# Maximum value FROM,TO is 3,4
(1/2 mark each for maximum value)
(1 mark for correct option)
5 Evaluate the following expressions:
a) 8 * 3 + 2**3 // 9 – 4
b) 12 > 15 and 8 > 12 or not 19 > 4
Answer a) 25
b) False
6 Differentiate between call by value and call by reference with a suitable example for each.
Answer In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-
value because you can not change the value of the immutable objects being passed to the function. Whereas passing
mutable objects can be considered as call by reference because when their values are changed inside the function, then it will
also be reflected outside the function.
7 Rewrite the following code in Python after removing all syntax
error(s). Underline each correction done in the code.
p=30
for c in range(0,p)
If c%4==0:
print (c*4)
Elseif c%5==0:
print (c+3)
else
print(c+10)
Answer p=30
for c in range(0,p):
if c%4==0:
print (c*4)
elif c%5==0:
print (c+3)
else:
print(c+10)
8 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 Lower and Upper.

import random

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

Lower =random.randint(1,4)

Upper =random.randint(2,5)

for K in range(Lower, Upper +1):

print (AR[K],end=”#“)

(i) 40# (ii) 40#50#60# (iii) 50# (iv) All of these

Answer (iv) All of these

9 Evaluate the following expression.


a) 51+4-3**3//19-3
b) 17<19 or 30>18 and not 19==0

Answer 51
True
10 What do you mean by keyword argument in python? Describe
with example.
Answer When you assign a value to the parameter (such as param=value)
and pass to the function (like fn(param=value)), then it turns into
a keyword argument.
11 Rewrite the following code in python after removing all
syntax errors. Underline each correction done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Answer def func(a): #def
s=m=n=0 #local variable
for i in (0,a): #indentation and frange function missing
if i%2==0:
s=s+I
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15) 2 marks for any four corrections.
12 What possible outputs(s) are expected to be displayed on screen 2
at the time of execution of the program from the following code.
Select which option/s is/are correct
import random
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' )
print((100) -random.randint(15,25) , end = ' ' )
print((100) *random.randint(15,25) )
(i) 15 122 84 2500
(ii) 21 120 76 1500
(iii) 105 107 105 1800
(iv) 110 105 105 1900
Answer (i ) (ii) are correct answers.
14 Predict the output of the following code. 2
def swap(P ,Q):
P,Q=Q,P
print( P,"#",Q)
return (P)
R=100
S=200
R=swap(R,S)
print(R,"#",S)
Answer
200 # 100
200 # 200
15 Evaluate the following expressions: 2
a) 6 * 3 + 4**2 // 5 – 8
b) 10 > 5 and 7 > 12 or not 18 > 3
Answer a) 13
c) False
output:
Inside add() : 12
In main: 15

18 Rewrite the following code in Python after removing all syntax


error(s).
Underline each correction done in the code.
Value=30
for val in range(0,Value)
If val%4==0:
print (val*4)
Elseif val%5==0:
print (val+3)
Else
print(val+10)
Answer Value=30
for VAL in range(0,Value) :
if val%4==0:
print (VAL*4)
elif val%5==0:
print (VAL+3)
else:
print(VAL+10
19 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 Lower and Upper.
import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,3)
Upper =random.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)

(i) 10#40#70#
(ii) 30#40#50#
(iii) 50#60#70#
(iv) 40#50#70#

Answer OUTPUT: (ii)


Maximum value of Lower: 3
Maximum value of Upper: 4
20 def simple_interest(p, r, t):
return (p*r*t)/100
print (simple_interest(100,5,2))
Identify the formal and actual parameters in the above code
snippet. Define formal and actual parameters in a function.
OR

Answer Answer: p,r,t is formal parameters and 100,5,2 are actual


parameters

21 c = 10
def add():
global c
c=c+2
print("Inside add():", c)

add()
c=15
print("In main:", c)

output:
Inside add() : 12
In main: 15
Consider the above program and justify the output. What is the
output if “global c “ is not written in the function add().

Answer Answer : In the function add() global c is increment due to use of


global keyword. In the main program local c is printed as local takes
precedence over global c.
If global c is not used then c=c+2 will show error as there is no
local variable c in function.
22 Consider the following function headers. Identify the correct
statement and state reason
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Answer 3) def correct(a=1,b=2,c=3):
Constant parameter can be used from right hand side.
23 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 AND minimum values that can be assigned
to the variable Num when P = 7

import random as r
val = 35
P=7
Num = 0
for i in range(1, 5):
Num = val + r.randint(0, P - 1)
print(Num, " $ ", end = "")
P=P-1
(a) 41 $ 38 $ 38 $ 37 $ (b) 38 $ 40 $ 37 $ 34 $
(c) 36 $ 35 $ 42 $ 37 $ (d) 40 $ 37 $ 39 $ 35 $

Answer (a) 41 $ 38 $ 38 $ 37 $
(d) 40 $ 37 $ 39 $ 35 $
Maximum value of Num when P = 7 : 42
Minimum value of Num when P = 7 : 35
24 Find the output of the following program;
def increment(n):
n.append([4])
return n
l=[1,2,3]
m=increment(l)
print(l,m)
Answer [1, 2, 3, [4]] [1, 2, 3, [4]]

25 Evaluate the following:


a. 45<89 and 7>12 or not 18>3
b. 6*3+2**4//5-2
Answer a. False
b. 19

1. Find and write the output of the following python code:


def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)

R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
Answer 250 # 150
250 # 100
130 # 100

(1 mark each for correct line)


2. Write a program in Python, which accepts a list Lst 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

Lst= [ 10,20,30,40,12,11], n=2

Output Lst = [30,40,12,11,10,20]

Answer L=len(Lst)
for x in range(0,n):
y=Lst[0]
for i in range(0,L-1):
Lst[i]=Lst[i+1]
Lst[L-1]=y
print(Lst)
#Note : Using of any correct code giving the same result
is also accepted.

3. Write a program in Python, which accepts a list Arr of


numbers , the function will replace the even number
by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:

arr=[10,20,23,45]
output : [10, 10, 115, 225]
Answer l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
print(arr)

1 mark for function


1 mark for loop and condition checking
1 mark for if and else
4 Write a program in Python, which accepts a list Arr 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
Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
Answer Arr= [ 10,20,30,40,12,11], n=2

L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
5 Write a program to reverse elements in a list where 3
arguments are start and end index of the list part which is
to be reversed. Assume that start<end, start>=0 and
end<len(list)
Sample Input Data of List
my_list=[1,2,3,4,5,6,7,8,9,10]
Output is
my_list=[1,2,3,7,6,5,4,8,9,10]
12
Answer my_mylist=[1,2,3,4,5,6,7,8,9,10]

l1=mylist[:start:1] ½ Mark
l2=mylist[end:start-1:-1] ½ Mark
l3=mylist[end+1:] ½ Mark
final_list=l1+l2+l3 ½ Mark
print (final_list) ½ Mark
Or any other relevant code
6 Write program to add those values in the list of 3
NUMBERS, which are odd.
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16
Answer NUMBERS=[20,40,10,5,12,11]
s=0
for i in NUMBERS:
if i%2 !=0:
s=s+i
print(s)
7 Write a program to replaces elements having even values 3
with its half and elements having odd values with twice its
value in a list.

eg: if the list contains


3, 4, 5, 16, 9
then rearranged list as
6, 2,10,8, 18
Answer L=[3, 4, 5, 16, 9]

for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
8 Write a Python program to find the maximum and minimum 3
elements in the list entered by the user.
Answer lst = []
num = int(input(“How many numbers”))

for n in range (nm):


numbers = int(input”Enter number :”))
lst.append(numbers)
print(“Maximum element in the list is :”,max(lst))
print(“Minimum element in the list is :”,min(lst))
9 Write a program in python to print b power p.
Answer b=int(input("Enter base number"))
p=int(input("Enter exp no."))
t=b
for i in range(p-1):
t=t*b
print(t)
10 Write a program to print of fibonnaci series upto n. 3
for example if n is 50 then output will be :
0
1
1
2
3
5
8
13
21
34
Answer n=int(input("Enter any nubmer"))
a=0
b=0
c=1
while a<=n:
print(a)
b=c
c=a
a=b+c

CHAPTER – 3 FUNCTIONS
Short Answer Type Questions – (1 mark for correct answer)
Q.1 Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Ans. 15
Q. 2. Trace the flow of execution for following program.
1 def power (b,p):
2 r = b**p
3 return r
4
5 def calcsquare(a):
6 a= power(a,2)
7 return a
8
9 n=5
10 result = calcsquare(n)
11 print(result)
Ans. 1→5→9→10→6→2→3→7→11

Q. 3. What will be the output of the following code?


def addEm(x,y,z):
print(x+y+z)

def prod(x,y,z):
return x*y*z

a= addEm(6,16,26)
b= prod(2,3,6)
print(a,b)
Ans. 48
None 36.

Short Answer Type Questions - (2 mark for correct answer)


Q. 1. Find and write the output of the following Python code:
def fun(s):
k= len(s)
m=""
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+'bb'
fun('school2@com')
Ans. SCHOOLbbbbCOM
Questions – 1 Mark - MCQ

Q1. To open a file c:\ss.txt for appending data we use


a. file = open(‘c:\\ss.txt’,’a’)
b. file = open(r‘c:\ss.txt’,’a’)
c. file = open(‘c:\\ss.txt’,’w’)
d. both a and b

Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file
immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above

Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown

Q6. How to open a file such that close function is not needed to be called in order
to close the connection between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
d. Using open with method
7. What is the full form of CSV?
a. Common segregated values
b. Comma separated values
c. Common separated values
d. None of the above

Q8. If a file is opened for writing


a. File must exist before opening
b. File will be created if does not exist
c. None of the above
d. Both a and b

Q9. If the cursor in the file is at the end of the file, then what will the read()
function return?
a. None
b. False
c. Exception
d. Empty string
Q10. Which is the value of mode parameter to set the offset of the cursor from the
end of the file?
a. 0
b. 1
c. 2
d. None of the above

Answer Key
1.d 2.c 3.c 4.c 5.b 6.c 7.b 8.a 9.d 10.c

You might also like