嵌套 if-else 语句
本课属于 Coddy Python 学习旅程的“基础知识”单元。第 23 课,共 77 课。
嵌套的 If-Else 语句可以让你通过在一个 if-else 语句中放入另一个语句来检查多个条件。你可以在 if 代码块中嵌套一个 else 代码块。这是 Python 中一种常见且有效的模式。
创建一个基本的 if-else 语句:
age = 18
title = ""
if age >= 18:
title = "Adult"
else:
title = "Minor"现在,我们在 else 代码块中添加一个嵌套条件:
age = 18
title = ""
allowed_to_drink = False
if age >= 18:
title = "Adult"
else:
title = "Minor"
if age >= 13:
title = "Teenager"
else:
title = "Child"你还可以在 if 代码块中嵌套一个条件:
age = 25
title = ""
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 语句只会在包含它的代码块运行时执行:位于 else 代码块中的语句会在 age >= 18 为 false 时执行,位于 if 代码块中的语句会在 age >= 18 为 true 时执行。在 else 代码块(或 if 代码块)中放置 if 语句完全合法。这正是它被称为“嵌套”的原因。
挑战
入门编写一个程序,根据年龄和父母陪同情况判断是否可以观看电影。
注意:age 和 with_parent 已经为你设置好,并且每个测试用例中的值都不同。不要自行设置它们,只需使用它们。
你的任务:
使用嵌套的 if-else 语句,将 message 变量设置为以下字符串之一:
- 如果 age 大于或等于 18,将
message设置为"You can watch any movie"。 - 如果 age 小于 18:
- 如果
with_parent是True,将message设置为"You can watch PG-13 movies"。 - 如果
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 代码
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Python 在线编译器