Test Series - python

Test Number 111/108

Q: How many except statements can a try-except block have?
A. 0
B. 1
C. more than one
D. more than zero
Solution: There has to be at least one except statement.
Q: 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
Solution: The else part is executed when no exception occurs.
Q: Is the following Python 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
Solution: Refer documentation.
Q: Is the following Python 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
Solution: Refer documentation.
Q: 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
Solution: Each type of exception can be specified directly. There is no need to put it in a list.
Q: 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
Solution: The finally block is always executed.
Q: What will be the output of the following Python code?

def foo():
    try:
        return 1
    finally:
        return 2
k = foo()
print(k)
A. error, there is more than one return statement in a single try-finally block
B. 1
C. 2
D. 3
Solution: The finally block is executed even there is a return statement in the try block.
Q: What will be the output of the following Python code?

def foo():
    try:
        print(1)
    finally:
        print(2)
foo()
A. 1 2
B. 1
C. 2
D. none of the mentioned
Solution: No error occurs in the try block so 1 is printed. Then the finally block is executed and 2 is printed.
Q: 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
Solution: It simply evaluates to False and does not raise any exception.

You Have Score    /9