python 整数比较确实很尴尬(看似简单)的错误
我有以下一段代码,它根本没有按照我期望的方式工作...
current_frame = 15 # just for showcasing purposes
g_ch = 7
if (current_frame != int(row[0])) and (int(row[1]) != g_ch):
current_frame = int(row[0])
print "curious================================="
print current_frame
print row
print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0])
print "========================================"
它针对任何特定情况进行打印:
curious=================================
15
['15', '1', 'more data'] 15 != 15 , False
========================================
显然,这甚至不应该输入 if 语句,因为相等性显示为 false。为什么会发生这种情况?
编辑:我也尝试过用 != 而不是“不是”,并得到了相同的结果。
I have the following piece of code which is not working the way I expect it to at all...
current_frame = 15 # just for showcasing purposes
g_ch = 7
if (current_frame != int(row[0])) and (int(row[1]) != g_ch):
current_frame = int(row[0])
print "curious================================="
print current_frame
print row
print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0])
print "========================================"
which prints for any specific case:
curious=================================
15
['15', '1', 'more data'] 15 != 15 , False
========================================
This should obviously never even enter the if statement, as the equality is showing false. Why is this happening?
edit: I have also tried this with != instead of 'is not', and gotten the same results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
值比较是使用
!=
运算符完成的,而不是使用is not
来完成的,后者比较对象标识。除此之外,我认为这是一个缩进问题。
Value comparisons are done with the
!=
operator, not withis not
, which compares object identity.Apart from that, I think it's an indentation problem.
简而言之,您需要使用
==
和!=
,而不是is
。is
比较对象同一性,而不是相等性。In short, you need to use
==
and!=
, and notis
.is
compares object identity, not equality.您可以在 if 内指定
current_frame = int(row[0])
,这会更改布尔表达式的值。You assign
current_frame = int(row[0])
inside the if, which changes the value of the boolean expression.