参加一个介绍课程,需要创建一个过度/不足的猜谜游戏。如果有人输入负数或非整数,我想通过创建错误来微调我的用户输入。我正确地报告了非整数错误,并且负回送正确,但否定将不会打印我的错误消息。
#Number of plays
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
except ValueError:
print ("Integer numbers only please.")
except:
if x <=0:
print ("Positive numbers only please.")
i = get_plays("\nHow many times would you like to play?")
print ("The game will play " +str(i)+" times.")
另外,如果我想使用类似的设置为1到20之间的任何负非整数产生错误,这看起来怎么样?
答案 0 :(得分:0)
问题在于本节
except:
if x <=0:
空except
子句会触发尚未发现的任何错误,但负数不会触发异常。你需要这样的东西。请注意,在try
子句中,我们可以继续进行,就像x
已经是int一样,因为我们可以假设没有抛出ValueError
。
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print ("Positive numbers only please.")
else:
return x
except ValueError:
print ("Integer numbers only please.")
答案 1 :(得分:0)
尝试:
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print("Positive numbers only please.")
continue
if x not in range(20):
print("Enter a number between 1 - 20.")
continue
return x
except ValueError:
print("Integer numbers only please.")
它只接受介于1到20之间的正数