如果陈述If和Else结果不起作用

时间:2018-06-14 01:43:56

标签: python-3.x

if choice == 'E':
    num1 = random.randint(1,5)
    num2 = random.randint(1,5)
    print("what is " + str(num1) + " + " + str(num2)+ "")
    time.sleep (1)
    answer = input("What is your answer?: ")
    qanswer = (num1 + num2)
    if answer == qanswer:
        print ("You got it right!")
    else:
        print ("You got it wrong...")

我的代码问题在于虽然num1 + num2 = qanswer,当我做if语句回答== qanswer时,它总是说我弄错了,对问题和代码的反馈一般都很感激,谢谢!

2 个答案:

答案 0 :(得分:0)

input命令读入一个字符串,即使您键入的内容恰好代表一个数字。

在尝试比较值之前将“answer”转换为整数:

answer = int(input("What is your answer?: "))
qanswer = (num1 + num2)

if answer == qanswer:
    print ("You got it right!")
else:
    print ("You got it wrong...")

答案 1 :(得分:0)

您忘记在为answer获取值时键入强制转换,因为input命令读取为字符串。在您的情况下,您只需将strint进行比较即可。根据你的代码 -

print(type(answer)) 
print(type(qanswer))

输出:

<class 'str'>
<class 'int'>

尝试以下内容

import random
import time

choice = 'E'

if choice == 'E':
    num1 = random.randint(1,5)
    num2 = random.randint(1,5)
    print("what is " + str(num1) + " + " + str(num2)+ "")
    time.sleep (1)
    answer = int(input("What is your answer?: "))
    qanswer = (num1 + num2)
    if answer == qanswer:
        print ("You got it right!")
    else:
        print ("You got it wrong...")