因此,一旦我运行代码,question()
就会返回'Incorrect'
,即使我非常确定我会给出正确答案。
P.S。我检查了operator()
函数是否合适;它只是需要注意的question()
。
import random
def numberRan(): # Generate a random number
return random.randint(1, 10) # No arguments needed for this
def operator():
operator = ""
number = random.randint(1, 3)
if number == 1:
operator = "+"
elif number == 2:
operator = "-"
else:
operator = "x"
return operator
def question():
num1 = numberRan()
num2 = numberRan()
realAnswer = 0
int(realAnswer)
oper = operator()
answer = input(str(num1) + str(oper) + str(num2) + "= ")
if oper == "+":
realAnswer = num1 + num2
elif oper == "-":
realAnswer = num1 - num2
elif oper == "x":
realAnswer = num1 * num2
if realAnswer == answer:
return "Correct"
else:
return "Incorrect"
question()
答案 0 :(得分:2)
你永远不会将你的答案转换为int,所以你的答案(input(...)
的结果仍然是str。你然后将str与realAnswer
进行比较,这是一个int:比较一个int和str将始终为False
。
只需更改一行:
answer = input(str(num1) + str(oper) + str(num2) + "= ")
到
try:
answer = int(input(str(num1) + str(oper) + str(num2) + "= "))
except ValueError:
import sys
sys.stderr.write("your input was not an integer number")
return "Incorrect"
if oper == "+":
...
请注意try-except子句:现在,如果输入不是数字,则会出现解释性错误消息。