为什么这个python的结果总是正确的?

2024-10-01 07:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

不管我给x或y写了什么数字

即使我改变了16或250的值

x = anyRandomNumber
y = anyRandomNumber
print ((x + y == 16) == ((10*x) + (25*y) == 250))

这是一个讲师在一节课上提供的代码,假设只有当x=10和y=6时才执行true

enter image description here


Tags: 代码true数字print讲师一节课anyrandomnumber
3条回答
x = 1
y = 1
print (x + y == 16)  # False
print ((10*x) + (25*y) == 250) # False
print ((x + y == 16) == ((10*x) + (25*y) == 250)) # False == False

x = 10
y = 6
print (x + y == 16)  # True
print ((10*x) + (25*y) == 250) # True
print ((x + y == 16) == ((10*x) + (25*y) == 250)) # True == True

因为False==False在python中是True,所以当x+y不是16,并且10x+25y不等于250时,整个语句的求值结果都是True。如果希望它按您所说的方式工作,则需要使用“and”运算符(“&;也工作”):

打印((x+y==16)和((10*x)+(25*y==250))

当您在程序中输入任意随机数时,表达式的两边都计算为False,因此整个表达式读取False == False,即True。一些数字(例如8和8)计算True == False,因此它输出False

相关问题 更多 >