Menu
CoddyTech

嵌套 if - else

本课属于 Coddy Python 学习旅程的“基础知识”单元。第 23 课,共 77 课。

嵌套的 If-Else 语句让你可以通过在一个 if-else 语句中放入另一个语句来检查多个条件。你可以在 if 代码块中嵌套一个 else 代码块。这是 Python 中常见且有效的模式。

创建一个基本的 if-else 语句:

age = 18
title = "None"
if age >= 18:
    title = "Adult"
else:
    title = "Minor"

现在,我们在 else 代码块中添加一个嵌套条件:

age = 18
title = "None"
allowed_to_drink = False
if age >= 18:
    title = "Adult"
else:
    title = "Minor"
    if age >= 13:
        title = "Teenager"
    else:
        title = "Child"

你也可以在 if 代码块中嵌套一个条件:

age = 25
title = "None"
allowed_to_drink = False
if age >= 18:
    title = "Adult"
    if age >= 21:
        allowed_to_drink = True
    else:
        allowed_to_drink = False
else:
    title = "Minor"

在这两个示例中,只有包含内部 if-else 的代码块运行时,内部 if-else 才会运行:位于 else 代码块中的那个会在 age >= 18 为 false 时运行,位于 if 代码块中的那个会在 age >= 18 为 true 时运行。在 else 代码块(或 if 代码块)中放置一条 if 语句完全有效。这正是它被称为“嵌套”的原因。

challenge icon

挑战

入门

编写一个程序,根据年龄和父母陪同情况判断是否可以观看电影。

注意:age 和 with_parent 已经为你设置好,并且每个测试用例中的值都不同。不要自己设置它们,只需使用它们。

你的任务:
使用嵌套的 if-else 语句,将 message 变量设为以下字符串之一:

  1. 如果年龄为 18 岁或以上,将 message 设为 "You can watch any movie"。
  2. 如果年龄未满 18 岁:
    1. 如果 with_parent 为 True,将 message 设为 "You can watch PG-13 movies"。
    2. 如果 with_parent 为 False,将 message 设为 "You can only watch G-rated movies"。

重要:由于 with_parent 已经是布尔值,请直接检查它(例如,if with_parent:),不要将它与 "true" 或 "True" 这样的字符串进行比较。

重要:字符串必须完全一致,包括大小写和标点。例如,使用 "PG-13 movies"(小写的 'm'),不要使用 "PG-13 Movies"。

亲手试试

# 在这里编写嵌套的 if-else 代码


# 不要修改此行以下的代码
print(message)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Python 在线编译器