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()
但它并没有阻止代码运行,错误仍然会弹出。
答案 0 :(得分:1)
发布的代码中没有分区,不抛出ZeroDivisionError。
当xyz / rolls
评估为0时,rolls
稍后 ( ),当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)")
评估为0时,可能会抛出异常。 / p>
修复逻辑,以便甚至不允许发生这种无效分割!也许“0”意味着退出游戏?或者“0”表示应该要求用户进行另一次滚动?
FWIW,这里是修改后的代码,用于读取不接受“0”的输入:
{{1}}