if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
guess = int(input(""))
if guess == answer:
print("Correct!")
score + 1
elif guess != answer:
print("Incorrect")
else:
except ValueError:
print("Expected integer")
我试过除了ValueError,但它声明它是无效的语法。我试图让代码强制用户为答案输入一个整数,如果他们没有,那么它会告诉他们他们应该输入一个整数。
答案 0 :(得分:0)
ValueError
不是函数;它是一个类(Exception
子类)。
您需要将except
用作try
语句的一部分,它不能单独使用;你需要提供你想要的任何代码并且保护'在try
:
if op == '+':
left1 = random.randint(1,100)
right1 = random.randint(1,100)
print ("What is " + (str(left1) + op + str(right1) + "?"))
answer = eval(str(left1) + op + str(right1))
try:
guess = int(input(""))
except ValueError:
print("Expected integer")
else:
if guess == answer:
print("Correct!")
score = score + 1 # don't forget to *store* the sum!
else:
print("Incorrect")
您可能希望阅读Python中有关用户输入的规范Stack Overflow问题,以了解有关此问题的更多信息:Asking the user for input until they give a valid response以及Python教程中的section on handling exceptions。