Test Series - python

Test Number 112/108

Q: What will be the output of the following Python code?

#generator
def f(x):
    yield x+1
g=f(8)
print(next(g))
A. 8
B. 9
C. 7
D. Error
Solution: The code shown above returns the value of the expression x+1, since we have used to keyword yield. The value of x is 8. Hence the output of the code is 9.
Q: What will be the output of the following Python code?

def f(x):
    yield x+1
    print("test")
    yield x+2
g=f(9)
A. Error
B. test
C. test 10 12
D. No output
Solution: The code shown above will not yield any output. This is because when we try to yield 9, and there is no next(g), the iteration stops. Hence there is no output.
Q: What will be the output of the following Python code?

def f(x):
    yield x+1
    print("test")
    yield x+2
g=f(10)
print(next(g))
print(next(g))
A. No output
B. 11 test 12
C. 11 test
D. 11
Solution: The code shown above results in the output:
11
test
12
This is because we have used next(g) twice. Had we not used next, there would be no output.
Q: What will be the output of the following Python code?

def f(x):
    for i in range(5):
        yield i
g=f(8)
print(list(g))
A. [0, 1, 2, 3, 4]
B. [1, 2, 3, 4, 5, 6, 7, 8]
C. [1, 2, 3, 4, 5]
D. [0, 1, 2, 3, 4, 5, 6, 7]
Solution: The output of the code shown above is a list containing whole numbers in the range (5). Hence the output of this code is: [0, 1, 2, 3, 4].
Q: The error displayed in the following Python code is?

import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)
print(next(l1))
A. ‘list’ object is not iterator
B. ‘tuple’ object is not iterator
C. ‘list’ object is iterator
D. ‘tuple’ object is iterator
Solution: The error raised in the code shown above is that: ‘tuple’ object is not iterator. Had we given l2 as argument to next, the error would have been: ‘list’ object is not iterator.
Q: Which of the following is not an exception handling keyword in Python?
A. try
B. except
C. accept
D. finally
Solution: The keywords ‘try’, ‘except’ and ‘finally’ are exception handling keywords in python whereas the word ‘accept’ is not a keyword at all.
Q: What will be the output of the following Python code?

g = (i for i in range(5))
type(g)
A. class <’loop’>
B. class <‘iteration’>
C. class <’range’>
D. class <’generator’>
Solution: Another way of creating a generator is to use parenthesis. Hence the output of the code shown above is: class<’generator’>.

You Have Score    /7