【发布时间】:2016-01-06 22:07:19
【问题描述】:
我正在尝试通过键入“exit”来退出下面的代码块。由于将输入语句格式化为整数,这导致了错误。我能够使用 try 和 except 摆脱错误,但是我仍然无法将“退出”识别为输入,因为所有非整数输入都会导致代码块底部的 else 打印语句,包括“出口'。
除了ValueError之外,还有什么方法可以评估变量吗?
import sys
import pdb
from random import choice
random1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
random2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
while True:
print("To exit this game type: 'exit'")
num1 = choice(random2)
num2 = choice(random1)
try:
answer = int(input("What is {} times {}? :" .format(num1,\
num2)))
if answer == num1 * num2:
print("Correct Choice!")
else:
print("WRONG")
except ValueError:
if answer == 'exit':
print("Now exiting the game")
sys.exit()
else:
print("that answer is not valid try again")
`
【问题讨论】:
标签: python-3.x exception-handling