为什么函数的整数返回值与整数

问题描述

为什么会这样?

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)

但不是这个?

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)

每次运行nextsquare都会返回一个整数,那么nextsquare第一次返回的区别是什么

for num in nextSquare():

for num in 1:

解决方法

每次运行nextsquare时返回一个整数

对,nextSquare 应该先“运行”。您可以像 nextSquare() 一样调用它,它返回一个可迭代对象,然后 for 循环对其进行迭代,如下所示:

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

然而,调用 next(1) 是没有意义的,因为迭代单个数字没有意义 - 循环迭代 collections 或“collection -像”。单个数字肯定不像集合,因此您无法对其进行迭代。

错误消息准确地说:

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