Truthy、True、Falsey 和 False
比较会检查真值性,但某个值"为真"(truthy)并不等同于它就是 True。其逆命题对"为假"(falsey)与 False 同样成立。因此,在检查某个东西是 True 或 False,与仅仅判断其真值性时,您需要格外留意。在 Python 中,is 运算符用于检查两个对象是否完全相同。本题将使用一个关于企鹅的详情记录字典,键与上一题相同(species、flipper_length、body_mass、sex),并新增了一个布尔型的 tracked 键。
我们已加载了一个字典 penguin_305_details,其中包含一只企鹅的全部数据。
本练习是课程的一部分
Python 的数据类型
练习说明
- 检查
penguin_305_details的sex键的真值性。- 若为真,检查
sex是否为True,并将结果存为sex_is_true。 - 打印
sex键和sex_is_true。
- 若为真,检查
- 检查
penguin_305_details的tracked键的真值性。- 若为真,检查
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"{____['____']}: {____}")