我試圖通過鍵入'退出'退出下面的代碼塊。由於將輸入語句的格式設置爲整數,導致出現錯誤。我能夠利用try和but除掉錯誤,但是我仍然無法將'exit'識別爲輸入,因爲所有非整數輸入都會導致代碼塊底部的else print語句包括'出口'。如果除了ValueError之外的其他工作python3(初學者)
除了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")
`
這種技巧正是我一直在試圖找出和完美。謝謝! – JimmyF