我是Python的初学者,在YouTube上看到了Cory Schafer关于布尔和条件的教程。当他试图展示Python认为哪些值为False时,他有一个片段。他一个接一个地测试它们,但我想知道是否有更有效/更有趣的方法可以做到这一点,所以我试着想出这个for循环语句。我期望输出为8行Evaluated to False,但我一直得到Evaluatedd 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
将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 ')
小心!您正在评估完整的元组,每次在循环中(因此,评估同一对象(,而不是单个项。此外,您得到的是True,因为非空列表/元组/字典的计算结果将始终为True,而空列表/tuples/dictionary的计算结果为False,正如您在最近3次迭代中看到的那样。
当您评估为i
而不是condition
:时,您应该更改行
condition = (False, None, 0, 0.00, '', (), [], {})
for i in condition:
if i:
print('Evaluated to True')
else:
print('Evaluated to False')
这理所当然地返回:
Evaluated to False
Evaluated to False
Evaluated to False
Evaluated to False
Evaluated to False
Evaluated to False
Evaluated to False
Evaluated to False
在if语句中将条件替换为i
condition = (False, None, 0, 0.00, '', (), [], {})
for i in condition:
if condition:
print("Evaluated to True")
else:
print("Evaluated to False")