为什么我的代码说答案错了?

时间:2017-08-31 16:53:11

标签: python

代码应该是一个简单的数学测验,然而,当我输入正确答案时,它说这是错误的。我的代码是:

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!")

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

您忘记将用户输入转换为int,因此将student = input()替换为student = int(input()),就像您将strint进行比较时一样。

答案 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。这可以帮助你加快速度。