【发布时间】:2015-10-20 09:03:29
【问题描述】:
我使用 Python 3 制作了一个测验程序。我正在尝试实施检查,以便在用户输入字符串时,控制台不会出现错误。我输入的代码不起作用,我不知道如何修复它。
import random
import operator
operation=[
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
print("Correct")
score += 1
try:
val = int(input())
except ValueError:
print("That's not a number!")
else:
print("Incorrect")
if num_of_q==10:
print(name,"you got",score,"/",num_of_q)
【问题讨论】:
-
有什么不好的?
-
如果我输入一个字符串,无论如何都会出现错误,如果我输入正确的答案,那么问题就会停止,我必须按 Enter 才能获得下一个问题。如果我答错了,什么也不会发生。
-
你的 if 语句
if int(input()) == op(num1, num2)在你的 try 语句之前将 str 转换为 int
标签: python python-3.x