为什么这些循环没有被执行?

时间:2015-07-14 20:10:53

标签: python python-3.x boolean

我正在尝试使用布尔值来更好地理解它们。 我的书说任何空类型的数据都被解释为“False”,任何非空类型的数据都被解释为“True”。当我编写以下程序时,我认为我会得到一个无限循环,但程序没有返回任何内容。

def main():
    while False == "":
        print("i")

main()

我也试过

def main():
    while True == "b":
        print("i")

main()

我还期望这是一个无限循环,但它什么都没有返回

4 个答案:

答案 0 :(得分:4)

True是一个布尔值,"b"是一个字符串。他们不平等。

但是,"b"是" truthy"

>>>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

注意整数。布尔子类int。 0不是真的:

if 1:
    print 'this will print'
if 0:
    print 'this will not print'

答案 1 :(得分:2)

虽然"空值被视为False",但这并不意味着False == ""是真正的表达式。这意味着以下将是一个无限循环:

while "b":
    print("i")

答案 2 :(得分:2)

对象的隐含真实性并不意味着它将与TrueFalse文字进行同等比较。

>>> False == ""
False
>>> True == "b"
False

这只意味着他们对bool

进行了转换(隐式或显式)
>>> bool("")
False
>>> bool("b")
True

这意味着您可以在if语句,any / all等语境中使用对象的隐含真实性。

if "b":

或者

while "b":

答案 3 :(得分:1)

正如其他人所说,''可能被视为假谓词("假名"值)但实际上并非False,而非空字符串是真实的,但实际上不是True

但是不要尝试使用if False == 0:,否则您将获得无限循环,因为bool数据类型是int数据类型的子类。如果您愿意,您甚至可以使用TrueFalse代替10进行数学运算。

相关问题