我得到了這個代碼
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 陳述句的行為方式應該相同。但布林值不是。我不明白為什么布林值會以某種方式變成 None。有人可以解釋發生了什么嗎?
uj5u.com熱心網友回復:
這個:
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 陳述句。它是用于不同目的的不同結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/340115.html
上一篇:如何在串列之外合并字典中的鍵?
