所以我最近在Codecademy上学习Python,我不小心提交了这个
def check_bit4(input):
if 0b1000 & input:
return "on"
else:
return "off"
作为我的代码,它应该是这样的(省略了 if 语句中的“> 0 ”)。由于某种原因,上面的代码仍然通过了所有给定的测试用例。
def check_bit4(input):
if 0b1000 & input > 0:
return "on"
else:
return "off"
最初的提示要求一个函数来检查第四位是否为“on”。据我所知,“&”运算符应该返回 int 值而不是 bool 值。所以,我的问题是,为什么第一个程序仍然通过了所有测试用例?
最佳答案
零被视为虚假值。其他数均视为真值:
>>> bool(1)
True
>>> bool(34)
True
>>> bool(0)
False
如果input
设置了位,0b1000 & input
将返回非零值。因此,如果满足该条件,谓词将被视为 true。
参见Truth Value Testing - Python documentation更精确地定义真值。
关于python - int 如何作为 bool 语句求值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818739/