代码应该是一个简单的数学测验,然而,当我输入正确答案时,它说这是错误的。我的代码是:
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
if student == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
有什么想法吗?
答案 0 :(得分:1)
您忘记将用户输入转换为int
,因此将student = input()
替换为student = int(input())
,就像您将str
与int
进行比较时一样。
答案 1 :(得分:1)
假设您使用的是Python 3,则需要输入强制转换input()
到int()
,以便将其与answer
进行比较,这是一个整数:
student = int(input())
答案 2 :(得分:1)
假设是python3。以下内容对python2无效,因为输入将整数输入视为整数。
python2中的input()在从stdin读取后用eval()函数计算表达式,从而返回一个整数。
问题依赖于您将字符串与答案进行比较的事实。
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
#Cast the input to an integer for comparison
if int(student) == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
答案 3 :(得分:0)
正如许多人已经说过的,你需要将用户输入转换为int,替换student = input()
此外,您可以question += 1
而不是question = question + 1
。这可以帮助你加快速度。