我正在尝试进行算术测验,但遇到了这个问题:即使我输入正确的答案,它似乎忽略了正确的答案代码并直接找到错误的答案代码。基本上,它不接受任何正确的答案。
import random
num1 = (random.randrange(10))
num2 = (random.randrange(10))
correct1 = (num1*num2)
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
if ans1 == correct1:
print("Correct! ")
if ans1 != correct1:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
跑步的时候,我得到这样的东西:
What is 3 multiplied by 0? 0
Incorrect.
The correct answer was 0
请注意答案和我的输入是一样的,但它运行代码以获得错误的答案。任何人都可以帮我解决这个问题吗?我使用的是Python 3.4。
答案 0 :(得分:1)
3
不等于"3"
。调用input
(在Python3中)的结果是字符串,而不是数字。
在用户输入上调用int
...
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
ans1 = int(ans1)
...
答案 1 :(得分:1)
if int(ans1) == correct1:
print("Correct! ")
else:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
您必须将数字与数字进行比较 你在比较'3'和3