为什么不执行这些循环?
Why are these loops not executed?
我正在尝试使用布尔值来更好地理解它们。
我的书上说,任何空类型的数据都被解释为 "False",任何非空类型的数据都被解释为 "True"。当我写下面的程序时,我以为我会得到一个无限循环,但是程序什么也没返回。
def main():
while False == "":
print("i")
main()
我也试过了
def main():
while True == "b":
print("i")
main()
我还以为这是一个无限循环,但它什么也没返回
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 语句中利用名称的 "truthiness":
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'
虽然 "an empty value is treated as False
" 为真,但这并不意味着 False == ""
为真表达式。这意味着以下将是一个无限循环:
while "b":
print("i")
一个对象隐含的真实性并不意味着它将与 True
和 False
文字进行同等比较。
>>> False == ""
False
>>> True == "b"
False
这只是意味着它们可以(隐式或显式)转换为 bool
>>> bool("")
False
>>> bool("b")
True
这意味着您可以在 if
语句、any
/all
等
的上下文中使用对象的隐式真实性
if "b":
或
while "b":
正如其他人所说,''
可能被视为假谓词("falsey" 值)但实际上不是 False
,非空字符串为真但实际上 True
.
但是不要尝试使用 if False == 0:
否则您确实会得到一个无限循环,因为 bool
数据类型是 int
数据类型的子类。如果愿意,您甚至可以使用 True
和 False
而不是 1
和 0
进行数学运算。
我正在尝试使用布尔值来更好地理解它们。 我的书上说,任何空类型的数据都被解释为 "False",任何非空类型的数据都被解释为 "True"。当我写下面的程序时,我以为我会得到一个无限循环,但是程序什么也没返回。
def main():
while False == "":
print("i")
main()
我也试过了
def main():
while True == "b":
print("i")
main()
我还以为这是一个无限循环,但它什么也没返回
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 语句中利用名称的 "truthiness":
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'
虽然 "an empty value is treated as False
" 为真,但这并不意味着 False == ""
为真表达式。这意味着以下将是一个无限循环:
while "b":
print("i")
一个对象隐含的真实性并不意味着它将与 True
和 False
文字进行同等比较。
>>> False == ""
False
>>> True == "b"
False
这只是意味着它们可以(隐式或显式)转换为 bool
>>> bool("")
False
>>> bool("b")
True
这意味着您可以在 if
语句、any
/all
等
if "b":
或
while "b":
正如其他人所说,''
可能被视为假谓词("falsey" 值)但实际上不是 False
,非空字符串为真但实际上 True
.
但是不要尝试使用 if False == 0:
否则您确实会得到一个无限循环,因为 bool
数据类型是 int
数据类型的子类。如果愿意,您甚至可以使用 True
和 False
而不是 1
和 0
进行数学运算。