我正在试验 boolean 值以更好地理解它们。 我的书说任何空类型的数据都被解释为“假”,任何非空类型的数据都被解释为“真”。当我写下面的程序时,我以为我会得到一个无限循环,但程序什么也没返回。
def main():
while False == "":
print("i")
main()
我也试过
def main():
while True == "b":
print("i")
main()
我还以为这是一个无限循环,但它什么也没返回
请您参考如下方法:
True 是一个 boolean 值,"b" 是一个字符串。它们不相等。
然而,“b”是“真实的”
>>>bool("b")
True
这就是为什么如果你想要一个无限循环,你可以执行以下操作:
while "my not empty string that is truthy":
do.something()
# This is the same as:
while True:
do.something()
您还可以在 if 语句中利用名称的“真实性”:
if "b": # "b" is 'truthy'
print 'this will be printed'
if "": # "" is not 'truthy'
print 'this will not be printed'
其他类型也是如此:
if ['non-empty', 'list']: # Truthy
if []: # Falsey
if {'not' : 'empty dict'}: # Truthy
if {}: # Falsey
小心整数。 boolean 子类 int。 0 不真实:
if 1:
print 'this will print'
if 0:
print 'this will not print'
