TypeError:“ NoneType”对象不可迭代当我在python中使用生成器时

时间:2019-03-28 19:07:15

标签: python python-3.x jupyter-notebook

我需要创建一个生成器,该生成器在高和低数字(即输入)之间产生“ n”个随机数。我设法做到了,但是我不明白为什么会发生错误。

我是用Jupyter Notebook在python中完成的。


import random
def rand_num(low,high,n):
    for x in range(n):
        print (random.randint(low,high))
--------------------------------------------
for num in rand_num(1,10,12):
    print(num)

我开始做,但是出现此错误:

8
8
2
10
4
4
3
10
1
4
6
3

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-f54bba9a72c6> in <module>()
----> 1 for num in rand_num(1,10,12):
      2     print(num)

TypeError: 'NoneType' object is not iterable

我需要帮助以了解此错误。为什么会这样?

1 个答案:

答案 0 :(得分:4)

可调用rand_num不会显式返回任何内容,这与返回None相同,因此您实际上是在写for num in None,这当然是不可能的。您正在寻找的是

import random

def rand_num(low, high, n):
    for x in range(n):
        yield random.randint(low, high)

for num in rand_num(1, 10, 12):
    print(num)