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.
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
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
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.
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.
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
hackadocka
Highly Voted 3 years, 10 months agoEfren
3 years, 7 months agokoyuul
3 years, 7 months agoEfren
Highly Voted 3 years, 7 months agozantrz
Most Recent 9 months, 2 weeks agoOracleist
9 months, 3 weeks agonatlal
10 months, 1 week agoEllo2023
1 year, 5 months agomlsc01
1 year, 9 months agoCAPTAINKURK
1 year, 10 months agoivanbicalho
2 years, 1 month agoPremJaguar
2 years, 4 months agomacxsz
2 years, 6 months agoTheNetworkStudent
2 years, 8 months agovidts
3 years, 7 months ago