首页 > 解决方案 > 如果写作的行为方式不同,为什么经典和内联?

问题描述

我得到了这个代码

firstId = True
       
for x in [1,2,3,4,5]:
    firstId = False if firstId else print(str(x)+ " " + str(firstId))
    
print ("What is happening here ???")

firstId = True
       
for x in [1,2,3,4,5]:
    if firstId: 
        firstId = False
    else:
        print(str(x)+ " " + str(firstId))

奇怪的是我有这个输出

2 False
3 None
4 None
5 None
What is happening here ???
2 False
3 False
4 False
5 False

据我了解,两个 if 语句的行为方式应该相同。但布尔值不是。我不明白为什么布尔值以某种方式变为无。有人可以解释发生了什么吗?

标签: pythonpython-3.xif-statement

解决方案


这个:

firstId = False if firstId else print(str(x)+ " " + str(firstId))

是相同的

firstId = (False if firstId else print(str(x)+ " " + str(firstId)))

IE

if firstId:
    firstId = False
else:
    firstId = print(str(x)+ " " + str(firstId))

它总是给 赋一个值firstId,右边的条件表达式决定了那个值是什么。

在这种else情况下,该值为 None,因为print(...)返回 None。

条件表达式不是单行 if 语句。它是用于不同目的的不同结构。


推荐阅读