0
while True:  #code should only allow integers to be inputed
        try: 
            rolls = int(input("Enter the number of rolls: "))
            break
        except:
            print("You did not enter a valid Integer")

输出适用于“b”和“d”等字符,但是当我输入零时,我仍然得到 ZeroDivisionError

我希望代码只允许一个整数。

后来在代码中我尝试了这个

if rolls <= 0:
    print("You must enter at least one roll")
    print()

但它不会阻止代码运行,并且仍然会弹出错误。

4

1 回答 1

1

发布的代码中没有除法,也不会抛出 ZeroDivisionError。

稍后xyz / rolls完成时(该 try/catch 之外),当计算结果为 0时,可能会引发异常。rolls

修复逻辑,甚至不允许发生这种无效的划分!也许“0”意味着退出游戏?或者也许“0”意味着应该要求用户再投一次?


FWIW,这里是修改后的代码来读取不接受“0”的输入:

while True:  #code should only allow integers to be inputed
    try: 
        rolls = int(input("Enter the number of rolls: "))
        if rolls > 0:
            break
    except:
        pass # don't do anything here, because we print below for
             # exceptions and when the if guarding the break failed.
    print("You must enter a valid roll (> 0)")
于 2013-11-03T19:08:01.227 回答