Truthy、True、Falsey 與 False
雖然比較運算會檢查 truthiness,但「truthy」不等於 True。反過來說,falsey 值也不等於 False。因此,當你要檢查某個東西是 True 或 False,和只檢查它是否為 truthy 或 falsey 時,要特別留意。在 Python 中,我們可以用 is 運算子來檢查兩個東西是否完全相同。這次你會使用一個企鵝資料紀錄的字典,鍵和上一個練習一樣(species、flipper_length、body_mass、sex),另外還有一個 tracked 鍵,其值為布林值。
我們已載入一個字典 penguin_305_details,其中包含單一一隻企鵝的所有資料細節。
本練習屬於課程
Python 的資料型別
練習說明
- 檢查
penguin_305_details的sex鍵是否為 truthy。- 若為 true,檢查
sex是否為True,並將結果儲存為sex_is_true。 - 列印
sex鍵的值與sex_is_true。
- 若為 true,檢查
- 檢查
penguin_305_details的tracked鍵是否為 truthy。- 若為 true,檢查
tracked是否為True,並將結果儲存為tracked_is_true。 - 列印
tracked鍵的值與tracked_is_true。
- 若為 true,檢查
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Check the truthiness of penguin_305_details sex key
if ____["____"]:
# If true, check if sex is True and store it as sex_is_true
sex_is_true = penguin_305_details["sex"] ____ ____
# Print the sex key's value and sex_is_true
print(f"{____['____']}: {____}")
# Check the truthiness of penguin_305_details tracked key
if ____["____"]:
# If true, check if tracked is True and store it as tracked_is_true
tracked_is_true = penguin_305_details["tracked"] ____ ____
# Print the tracked key and tracked_is_true
print(f"{____['____']}: {____}")