MCQ

Python MCQ and Answers – Part 16

This collection of Python Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer.
 

1. When will the “else” block of “try-except-else” be executed?

A Always

B When an exception is thrown

C When an exception is thrown in the “except” block

D When no exception is thrown

D
The “else” block is executed when no exception is thrown. Let’s take an example :

try:
    print(1 / 1)
except ZeroDivisionError as error:
    print(error)
else:
    print('Executing the else clause.')

Output:

1.0
Executing the else clause.
 

2. What is the output of the following code?
def f(i, l = []):
    l.append(i)
    return l
 
f(1)
f(2)
x = f(3)
print(x)

A 1 2 3

B [1, 2, 3]

C [1] [1, 2] [1, 2, 3]

D [1] [2] [3]  
 

B
 

3. What is the output of the following code?
x = {1:1, 2:4, 3:9}  

print(x.pop(2))  
print(x)

A 16 {1: 1, 3: 9}

B 4 {1: 1, 2:4}

C 4
       {1: 1, 3: 9}

D 16 {1: 1, 2:4}

C
 

4. How to create an iterator object from a list?

A By giving the list to the iter() function.

B Using a for loop.

C Using a while loop.

D You cannot create an iterable object from a list.

A
Let’s take an example :

x = iter(list(range(10)))
for i in x:
   print(i)
   next(x)

Output:

0
2
4
6
8
 

5. What is the output of the following code?
def f(x):
    yield x+1
    print("msg")
    yield x+1
h=f(4)

A msg

B msg2

C Error

D The code does not display anything

D
The above code will not produce any output. Indeed, when we try to give 4, and it does not have “next(h)”, the iteration stops. So there is no output.
 

6. What is the output of the following code?
list1 = ['Alex', 'Bob', 'Jean']
 
if 'alex' in list1:
    print(1)
else:
    print(2)

A 1

B 2

C Error

D None

B
Python language is case sensitive
 

7. What is the output of the following code os.listdir()?

A Displays the current working directory.

B Displays all directories within a given directory.

C Displays all directories and files in a given directory.

D Create a new directory.

C
 

8. Which of the following statements is correct?

A An exception is an error that occurs during execution.

B A syntax error is also an exception.

C An exception is used to exclude a block of code in Python.

D All the answers are true

A
 

9. For which the “in” operator can be used to check if an element is present there?

A List

B Dictionary

C Set

D All the answers are true

D
The “in” operator can be used in all data structures.
 

10. What is the output of the following code?
l1 = [1, 2, 3]
l2 = [4, 5, 6]
 
print(len(l1 + l2))

A 3

B 6

C 1

D Error

B
The + operator adds all the items to a new list.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *