-3

所以刚开始学习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 行,我不想用它淹没人们。一旦我回到家,我会发布整个事情。

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

4

1 回答 1

1

您的函数似乎没有roll_dice()返回任何内容,从而导致 TypeError。它“看起来”像程序循环一次的原因是因为在 for 循环之前的那一行调用了该函数。

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

while True:
    type = roll_dice()
    if type != 'a' and type != 'i':
        break
于 2018-07-18T01:10:11.593 回答