【问题标题】:Program will not compare the real answer to the players answer程序不会将真实答案与玩家答案进行比较
【发布时间】:2015-05-05 07:10:32
【问题描述】:

当我运行程序时,我会输入正确答案,但它总是将其标记为错误:

(10, '+', 2)
12
...
错误答案,答案是 12 !

这是错误的代码部分:

Player_answer = input()
print ("...")
time.sleep (0.5)

if operation==("+"): #check answer
    answer = num1+num2  #This works out the real answer

    if Player_answer == answer:  #This works out if the player is correct
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

if operation==("*"):
    answer = num1*num2

    if Player_answer == answer:
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

elif operation==("-"):
    answer = num1-num2

    if Player_answer == answer:
        print("That's the correct answer")
        score = score + 1
    else:
        print("Wrong answer, the answer was",answer,"!")

【问题讨论】:

  • 试试if int(Player_answer) == answer
  • 检查您从玩家那里得到的答案类型。添加打印类型(Player_answer)

标签: variables python-3.x


【解决方案1】:

默认情况下,input() 返回一个字符串。因此,即使您输入 12,Player_input 也是 "12"(一个字符串)。要使Player_input 成为integer,只需键入Player_input = int(Player_input)int() 函数接受任何数据值,并尝试将其转换为整数。但是,如果它无法转换,例如尝试转换"not num",它会引发ValueError。为了防止这种情况,您可以将其包装在try/except 语句中。

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2021-01-28
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多