What is the expected behavior of the following code?
It will:
What is the expected behavior of the following code?
It will:
B
>>> def f(n): ... for i in range (1,n+1): ... yield I ... >>> print(f(2)) <generator object f at 0x0000013BA21A82A0> ANswer is correct
yield keyword expression is I (capital i), while for loop variable is i (small I). Function is erroneous.
It works for me even is i and I, check my code up
the capital I would cause an error if you were to iterate through actual generator obj, for example in [for i in f(2)] there would be a NameError. However, in this code the obj is never ran so no error occurs.
if you try to loop through the generator, it will error. This won't happen because it's simply printed. Code is erroneous, but won't result in an error if executed in this manner. Answer B is correct.
def f(n): for i in range(1,n+1): yield i print(f(2)) #output: <generator object f at 0x000001C77ED4D000> generator=f(2) print(next(generator)) #output: 1 print(next(generator)) #output: 2 print(next(generator)) #output: StopIteration
Yield I is not the same as the variable name i. Which should mean runtime error.
The NameError is not raised because the generator is not executed at all. It's defined and only its reference is used. If it is executed in a loop or comprehension or by using next() then only the NameError will be raised.
This question is SO TRICKY. yield I, or yield X or yield ANYTHING, doesn't matter because in the code the undefined variable "I" is never reached. As the answer below from TheNetworkStudent, the answer is B.
answer is correct
The answers in the dumps are good to remember! The bulk of the exam questions are from these exam dumps. The questions with mistakes in them or missing : etc are in the exam but in the correct answer form, do remember the correct answers as well as the answers with the mistakes in the coding. There are a few questions that are slightly different but you can find the answers from the previous or next question/answers! Hope this helps!
yield control the flow of a generator. than if we use I instead of the variable name i, it will return an object that represent a generator.
def f(n): for i in range(1,n+1): yield i print(f(2)) #<generator object f at 0x00000220062CB140> for x in f(2): print(x, end='') #12 def f(n): for i in range(1,n+1): yield I for x in f(2): print(x, end=' ') #NameError: name 'I' is not defined
yield automatically creates, __iter__() and next() function. assuming it was yeild i. then to print, we would need print(next(f(2)))
answer is c because variable names are case sensitive
B. print <generator object f at (some hex digits)>