python - 用户在 python 3.4.3 版中正确回答后如何打印 "correct"

标签 python

这是我当前的代码,它打印 1 到 20 之间的两个随机数,并要求用户将它们相加。当答案被正确回答时,我希望它说正确,但我不确定如何做到这一点。

程序运行良好,但当用户输入正确答案时,什么也没有发生。

from random import randint


def Add(x, y):

    return x + y


num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = input("What is the answer to the question: ")

if ("answer") is (num1 + num2):
    print("Correct")

最佳答案

您需要将input 转换为int,使用实际的variable answer 并且不要使用is为了测试相等性,应该使用 is 来检查identity,并且在您的情况下对于数字 > 256 将失败:

num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = int(input("What is the answer to the question: "))

if  answer ==  num1 + num2:
    print("Correct")

为什么不应该使用:

In [35]: i = 256

In [36]: j = 256

In [37]:  i is j
Out[37]: True

In [38]: i = 257

In [39]: j = 257

In [40]:  i is j
Out[40]: False

对于 256,i is j 为 True 的唯一原因是因为 python 缓存从 -5 到 256 的小整数。

关于python - 用户在 python 3.4.3 版中正确回答后如何打印 "correct",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30111717/

相关文章:

python - 如何忽略位于括号中的链接?

python - Webapp2返回状态码418的方法

python - 从左到右填充 pandas 列

python - 如何使用 CSV 为使用 Bokeh 的 vbar 提供数据?

python - 运行多个python脚本和多处理有什么区别

python - Python 中的反射 : how to view all parameters of a function in Python 2. 7

简化 2 个 pandas 列与条件相乘的 Pythonic 方法

python - 为什么 <class 'numpy.float64' > 类型的 nan 返回 -9223372036854775808 作为 int64?

python - IOError: CRC 检查失败 0xffca51ff != 0x3679ba0L

python - 如何保存字符串的顺序?(Python 3.)