1

Why does this work?

def nextSquare():
    i = 1;

    # An Infinite loop to generate squares
    while True:
        yield i*i
        i += 1  # Next execution resumes
                # from this point

# Driver code to test above generator
# function
for num in nextSquare():
    if num > 100:
        break
    print(num)

But not this?

def nextSquare():
    i = 1;

    # An Infinite loop to generate squares
    while True:
        yield i*i
        i += 1  # Next execution resumes
                # from this point

# Driver code to test above generator
# function
for num in 1:
    if num > 100:
        break
    print(num)

An integer is returned each time nextsquare is run so what is the difference between the first time nextsquare returns in

for num in nextSquare():

and

for num in 1:
kpopgirl
  • 13
  • 2
  • 1
    that is a very abstract question. Do you want a solution, or a python implementation and design tradeoffs discussion? – ricoms Jan 31 '21 at 14:09
  • Does this answer your question? [What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) – ricoms Jan 31 '21 at 14:12

1 Answers1

1

An integer is returned each time nextsquare is run

Right, nextSquare should be "run" first. You call it like nextSquare(), it returns an iterable, then the for loop iterates over it, like this:

retval = nextSquare()
it = iter(retval)
num = next(it)
while True:
    # loop body
    try:
        num = next(it)
    except StopIteration:
        break

However, it doesn't make sense to call next(1), as it doesn't make sense to iterate over one single number - loops iterate over collections or something that is "collection-like". A single number certainly isn't anything like a collection, so you can't iterate over it.

The error message says exactly that:

>>> for _ in 1:
...  ...
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
ForceBru
  • 43,482
  • 10
  • 63
  • 98