Python 嵌套 If

Python 嵌套 If 语句是指将一个 If 语句放置在另一个 If 语句中。Python If Else 语句允许我们根据表达式结果(真、假)打印不同的语句。有时,即使条件为真,我们仍需要进一步检查。在这些情况下,我们可以使用嵌套 IF 语句,但使用时要小心。

在 Python 嵌套 if 语句示例中,如果一个人年龄在 18 岁或以上,则他有资格工作。否则,他没有资格。然而,公司不会给每个人都提供工作。因此,我们使用另一个名为嵌套 If 语句的 If 条件来检查他的教育资格或任何特定的公司要求。

Python 嵌套 If 语句语法

嵌套 If 语句的语法如下所示。

if ( test condition 1):
    # If test condition 1 is TRUE, then it checks for test condition 2
    if ( test condition 2):
         # If test condition 2 is TRUE, then these true lines executed
         Test condition 2 True statements
    else:
         # If test condition 2 is FALSE, then these false lines executed
         Test condition 2 False statements
else:
    # If test condition 1 is FALSE, then these lines executed
    Test condition 1 False lines

一旦我们在分号后按下回车键,它就会以制表符空格开始新的一行,这个制表符空格在其他编程语言中充当大括号 ({ })。

如果上述结构中存在的第一个测试条件为真,则它会进入 Python 嵌套 if 语句。

  • 如果测试条件 2 为真,则执行测试条件 2 真语句。
  • 否则(这意味着测试条件 2 为假),执行测试条件 2 假代码。

如果测试条件 1 为假,则执行测试条件 2 假语句。通过单击退格键,我们可以退出 If Else 块。

Python 嵌套 If 流程图

以下流程图将完美地解释您的嵌套 If 语句。

FLOW CHART For Nested If Statement

如果测试条件 1 为 FALSE,则执行 STATEMENT3。如果测试条件 1 为 TRUE,则检查测试条件 2,如果为 TRUE,则执行 STATEMENT1,否则执行 STATEMENT2。

Python 嵌套 If 示例

在这个嵌套 If 程序中,用户可以输入他的年龄,我们将把它存储在变量 age 中。如果年龄小于 18 岁,我们将打印两行。当条件失败时,我们再检查一个条件(嵌套),如果它成功,我们打印一些内容。如果嵌套条件失败,我们使用嵌套 if 语句打印其他代码。为了演示这一点,请在新文件中添加以下脚本。

age = int(input(" Please Enter Your Age Here:  "))
if age < 18:
    print(" You are Minor ") 
    print(" You are not Eligible to Work ") 
else:
    if age >= 18 and age <= 60:
        print(" You are Eligible to Work ")
        print(" Please fill in your details and apply")
    else:
        print(" You are too old to work as per the Government rules")
        print(" Please Collect your pension!")

请保存 Python 嵌套 If 文件并通过选择“运行模块”或按 F5 运行脚本。一旦您单击“运行模块”,我们的 Shell 将弹出消息“请在此处输入您的年龄:”。

输出 1:在这里,我们输入了 14 岁。第一个 If 条件为 TRUE,因此输出显示 If 块内的打印函数。

Please Enter Your Age Here: 14
You are Minor
You are not Eligible to Work

在这里,我们输入了年龄 = 27。第一个 If 条件为 FALSE。所以,它将进入 else 块,并在那里检查另一个条件。在这里,嵌套 If 语句为 TRUE,因此输出显示其中的打印函数。

Please Enter Your Age Here: 27
You are Eligible to Work
Please fill in your details and apply

我们输入了年龄 = 61。第一个 If 条件为 FALSE。所以,它将进入 else 块,并在那里检查其他条件。在这里,嵌套 If 语句也为 FALSE,因此输出显示 else 块内的打印函数。

Python Nested If Statement 6

在此嵌套 If 语句示例中,首先,我们声明了 age 变量。接下来,它要求用户输入任何整数值。int() 限制用户不能输入非整数值。

age = int(input(" Please Enter Your Age Here:  "))

如果此人年龄小于 18 岁,则将打印以下代码。

 print(" You are Minor ") 
 print(" You are not Eligible to Work ")

如果此人年龄大于或等于 18 岁,则第一个条件失败,因此它检查 else 语句。在 Else 语句中,还有另一个 if 条件(称为嵌套 If)。

Python 嵌套 IF 语句将检查此人年龄是否大于或等于 18 岁且小于或等于 60 岁。当条件为 TRUE 时,将打印以下代码。

 print(" You are Eligible to Work ")
 print(" Please fill in your details and apply")

当嵌套 If 中的条件为 FALSE 时。然后它将检查 else 块并打印以下代码行。请参阅 If ElseIf condition 文章。

 print(" You are too old to work as per the Government rules")
 print(" Please Collect your pension!")