ANALYSIS
嵌套 If 语句
# 语法
随着我们的程序变得越来越长、越来越复杂,我们的代码决策也变得越来越复杂。您可能已经遇到过这样的情况:在某个条件为真之后,您想检查另一个条件。
你知道我们还能做什么 if/elif/else 声明?
我们可以把它们嵌套在一起!🪹
一个 嵌套 if 语句 是 if 声明 里面 另一个 if 陈述。
假设我们有一个简单的 if/else 声明:
PRTCL // PY
if age >= 18: print('You are old enough to apply for a loan.')else: print('You are too young to apply for a loan.')让我们再添加一个if/else 语句嵌套在外部 if 声明:
PRTCL // PY
if age >= 18: if income >= 20000: print('You are eligible for a loan.') else: print('Your income is too low to be eligible for a loan.')else: print('You are too young to apply for a loan.')在 Python 中,缩进是确定嵌套级别的唯一方法。因为第 2-5 行缩进更多,所以它位于外部内部 if 陈述。
这是程序的控制流程:

注: 但请注意。将这些语句嵌套得太深(超过 2-3 个级别)通常不是一个好主意,因为这可能会使您的程序难以阅读。
# 示例
以下示例说明了嵌套控制流语句如何影响程序的输出:
PRTCL // PY
weather = 'Sunny'humidity = 35
if weather == 'Sunny': if humidity < 60: print('Let's go to the beach! 🏖️') else: print('Hmm, it's a little humid for a beach day.')else: print('It's not sunny today... let's try for another day.')这将打印以下内容:
PRTCL // OUTPUT
Let's go to the beach! 🏖️如果 humidity 为 65,则输出为:
PRTCL // OUTPUT
Hmm, it's a little humid for a beach day.现在您可以为您的程序添加多层决策!
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.04.08
Auth_Verified: 2026.04.08
