开始使用免费开始使用

Truthy、True、Falsey 和 False

比较会检查真值性,但某个值"为真"(truthy)并不等同于它就是 True。其逆命题对"为假"(falsey)与 False 同样成立。因此,在检查某个东西是 TrueFalse,与仅仅判断其真值性时,您需要格外留意。在 Python 中,is 运算符用于检查两个对象是否完全相同。本题将使用一个关于企鹅的详情记录字典,键与上一题相同(speciesflipper_lengthbody_masssex),并新增了一个布尔型的 tracked 键。

我们已加载了一个字典 penguin_305_details,其中包含一只企鹅的全部数据。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • 检查 penguin_305_detailssex 键的真值性。
    • 若为真,检查 sex 是否为 True,并将结果存为 sex_is_true
    • 打印 sex 键和 sex_is_true
  • 检查 penguin_305_detailstracked 键的真值性。
    • 若为真,检查 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"{____['____']}: {____}")
编辑并运行代码