Python 简明教程
Python - Nested if Statement
Python 支持 nested if statements ,这意味着我们可以在现有 if statement 中使用条件 if 和 if…else statement 。
Python supports nested if statements which means we can use a conditional if and if…else statement inside an existing if statement.
在初始条件变为真之后,可能会出现需要检查其他条件的情况。在这种情况下,可以使用嵌套 if 构造。
There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nested if construct.
此外,在嵌套 if 构造内,可以将 if…elif…else 构造包含在另一个 if…elif…else 构造内。
Additionally, within a nested if construct, you can include an if…elif…else construct inside another if…elif…else construct.
Syntax of Nested if Statement
带有 else 条件的嵌套 if 构造的语法如下:
The syntax of the nested if construct with else condition will be like this −
if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)
Flowchart of Nested if Statement
以下是 Python 嵌套 if 语句的流程图:
Following is the flowchart of Python nested if statement −
Example of Nested if Statement
以下示例演示了嵌套 if 语句的工作方式:
The below example shows the working of nested if statements −
num = 36
print ("num = ", num)
if num % 2 == 0:
if num % 3 == 0:
print ("Divisible by 3 and 2")
print("....execution ends....")
运行上述代码时,将显示以下结果:
When you run the above code, it will display the following result −
num = 36
Divisible by 3 and 2
....execution ends....
Nested if Statement with else Condition
如前所述,我们可以在 if 语句中嵌套 if-else 语句。如果 if 条件为真,则执行第一个 if-else 语句,否则将执行 else 块内的语句。
As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is true, the first if-else statement will be executed otherwise, statements inside the else block will be executed.
Syntax
带有 else 条件的嵌套 if 构造的语法如下:
The syntax of the nested if construct with else condition will be like this −
if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)
Example
现在让我们来看一个 Python 代码来了解它的工作原理 −
Now let’s take a Python code to understand how it works −
num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
当执行以上代码时,它会产生以下 output -
When the above code is executed, it produces the following output −
num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3