簡體   English   中英

盡管觸發了適當的 boolean 值,但如果語句不起作用 | Python

[英]If statement not working despite having triggered the appropriate boolean value | Python

我想在good_view_listTrue時執行這個 if 語句,我知道它是一個列表,但是每當我打印出它的 boolean 它給我一個True值(我假設因為里面有字符串),為什么不if good_view_time is True: good_view_time True if 語句有效。

我知道其他選擇,只是想知道為什么這個不起作用。

good_view_time = ['https://www.instagram.com/p/CKmTcvmHYkY/', 'https://www.instagram.com/p/CKcOxtlHJsy/' , 'https://www.instagram.com/p/CKpHBAcHkhl/']

#returns True
print(bool(good_view_time))

if good_view_time is True:
    for post in good_view_time:

        print(post)

bool(good_view_time)返回True ,但good_view_time本身是一個列表,它不能是字面上True good_view_time不是True ,但將其轉換為 Boolean 會給出 True ,因為非空列表是真實的。 同樣, bool("Hello") is True ,但字符串"Hello"本身絕對不等於 True (為什么會這樣?它是一個字符串,), is完全等同於True運營商會檢查。

所以,你應該比較:

if bool(good_view_time) is True:

或者,這是等效的:

if good_view_time:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM