開始使用免費開始

Truthy、True、Falsey 與 False

雖然比較運算會檢查 truthiness,但「truthy」不等於 True。反過來說,falsey 值也不等於 False。因此,當你要檢查某個東西是 TrueFalse,和只檢查它是否為 truthy 或 falsey 時,要特別留意。在 Python 中,我們可以用 is 運算子來檢查兩個東西是否完全相同。這次你會使用一個企鵝資料紀錄的字典,鍵和上一個練習一樣(speciesflipper_lengthbody_masssex),另外還有一個 tracked 鍵,其值為布林值。

我們已載入一個字典 penguin_305_details,其中包含單一一隻企鵝的所有資料細節。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • 檢查 penguin_305_detailssex 鍵是否為 truthy。
    • 若為 true,檢查 sex 是否為 True,並將結果儲存為 sex_is_true
    • 列印 sex 鍵的值與 sex_is_true
  • 檢查 penguin_305_detailstracked 鍵是否為 truthy。
    • 若為 true,檢查 tracked 是否為 True,並將結果儲存為 tracked_is_true
    • 列印 tracked 鍵的值與 tracked_is_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"{____['____']}: {____}")
編輯並執行程式碼