Q: What will be the output of the following Python code? #generator def f(x): yield x+1 g=f(8) print(next(g))
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)
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))
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))
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))
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?
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)
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 |