无法使程序正确迭代(TypeError:“ NoneType”对象不可迭代)

时间:2018-07-18 00:56:03

标签: python

所以刚开始学习python。在实践中,我决定构建一个程序来处理我对D&D角色的攻击,而我似乎不太可能正确地进行迭代。

from random import randint

def roll_dice():
    type = raw_input("Initiative (i) or Attack (a): ") #variable that is passed through the function
    roll = randint(1,20)
    if roll == 1:
        print "Natural 1"
    elif roll == 20:
        print "Natural 20"
    else:
        crit = "n"
    if type == 'i':
        result = roll + 5
        print "Initiative = %d" % result
        return 
    elif type == 'a':
""" most of the rest of the program is after here but that all works fine so there is no reason to take up space with that""" 

roll_dice()
for type in roll_dice():
    if type == 'a' or type == 'i':
        continue

程序将循环一次,然后显示:

TypeError:“ NoneType”对象不可迭代

我知道这意味着第二次迭代它没有通过任何东西,但我不太想知道如何解决它。

任何帮助和/或解释将不胜感激

编辑: 我知道它不会按发布的方式运行。整个过程超过了100行,我不想以此淹没人们。一回到家,我就会把整件事都贴出来。

为澄清起见:对于整个程序,它将循环运行一次回到起点,然后在完成第二次运行后返回错误。因此,循环的第一次工作是在完成第二次运行并尝试开始第三次运行之后。

1 个答案:

答案 0 :(得分:1)

您的roll_dice()函数似乎未返回任何东西,从而导致TypeError。之所以像程序一次循环那样“似乎”,是因为for循环之前的那一行调用了该函数。

您似乎想做的是从函数内部提取type变量,可以通过使用return type而不是return返回类型并使用来完成仅if语句。要循环直到type不是aiwhile循环可能会更有用,就像这样:

while True:
    type = roll_dice()
    if type != 'a' and type != 'i':
        break