Die*_*eve 0 python boolean-logic for-loop boolean python-3.x
我是 Python 的初学者,我在 YouTube 上看到了 Cory Schafer 关于布尔值和条件的教程。当他试图展示 Python 认为哪些值是 False 时,他有一个片段。他一一测试,但我想知道是否有更有效/更有趣的方法来做到这一点,所以我尝试提出这个 for 循环语句。我期望输出为 8 行 Evaluated to False,但我一直得到 Evaluated to True。有人可以启发我吗?谢谢!
condition = (False, None, 0, 0.00, '', (), [], {})
for i in condition:
if condition: # It is assumed that condition == true here, right?
print('Evaluated to True')
else:
print('Evaluated to False ')
#OUT:
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Run Code Online (Sandbox Code Playgroud)
更改if condition
为if i
。您想要测试从condition
元组中取出的每个单独项目,而不是测试整个元组 8 次。
更清晰的命名可以避免这个问题。我建议总是给集合以复数名称s
结尾。然后你可以写这个,它读起来更自然:
conditions = (False, None, 0, 0.00, '', (), [], {})
for condition in conditions:
if condition: # It is assumed that condition == true here, right?
print('Evaluated to True')
else:
print('Evaluated to False ')
Run Code Online (Sandbox Code Playgroud)