Python 中的 if…else 语句是什么?

当我们只想在满足特定条件时执行代码时,需要做出决策。
该if…elif…else语句在 Python 中用于决策。

Python if 语句语法

如果测试表达式: 声明
此处,程序test expression仅在测试表达式为 时才计算并且将执行语句True。
如果测试表达式为False,则不执行语句。
在 Python 中,if语句的主体由缩进表示。正文以缩进开始,第一个未缩进的行标志着结束。
Python 将非零值解释为True. None并被0解释为False。

Python if 语句流程图

image.png
Python编程中if语句的流程图

示例:Python if 语句

If the number is positive, we print an appropriate message num = 3 if num > 0: print(num, “is a positive number.”) print(“This is always printed.”) num = -1 if num > 0: print(num, “is a positive number.”) print(“This is also always printed.”)
当你运行程序时,输出将是:
3 是一个正数 这总是打印 这也总是打印。

在上面的例子中,num > 0是测试表达式。
if仅当 this 计算为 时才执行主体True。
当变量 数量等于 3,测试表达式为真,if执行主体内的语句。
如果变量 数量等于 -1,测试表达式为假并且if跳过主体内的语句。
该print()语句位于if块之外(未缩进)。因此,它的执行与测试表达式无关。


Python if…else 语句

if…else 的语法

如果测试表达式: if 的主体 别的: else 的身体
该if..else语句仅在测试条件为 时评估test expression并执行 的主体。ifTrue
如果条件为False,else则执行的主体。缩进用于分隔块。

Python if..else流程图

image.png
Python中if…else语句的流程图

if…else 的例子

Program checks if the number is positive or negative # And displays an appropriate message num = 3 # Try these two variations as well. # num = -5 # num = 0 if num >= 0: print(“Positive or Zero”) else: print(“Negative number”)
输出
正或零
在上面的例子中,当 数量等于3,测试表达式为真和的主体if被执行并且body的否则跳过。
如果 数量等于-5,测试表达式为假,else执行体,if跳过体。
如果 数量等于 0,测试表达式为真,if执行主体,body跳过 else。


Python if…elif…else 语句

if…elif…else 的语法

如果测试表达式: if 的主体 elif 测试表达式: elif 的身体 别的: else 的身体
的elif是短期的,如果别的。它允许我们检查多个表达式。
如果该条件if就是False,它检查下一个的条件elif的块等。
如果所有条件都满足False,则执行 else 的主体。
if…elif…else根据条件只执行几个程序段中的一个程序段。
该if块只能有一个else块。但它可以有多个elif块。

if…elif…else 的流程图

image.png
Python中if…elif….else语句的流程图

if…elif…else 的示例

‘’’In this program, we check if the number is positive or negative or zero and display an appropriate message’’’ num = 3.4 # Try these two variations as well: # num = 0 # num = -4.5 if num > 0: print(“Positive number”) elif num == 0: print(“Zero”) else: print(“Negative number”)
当变量 数量 是积极的, 正数 被打印。
如果 数量 等于0, 零 被打印。
如果 数量 是否定的, 负数 被打印。


Python 嵌套 if 语句

我们可以if…elif…else在另一个if…elif…else语句中包含一个语句。这在计算机编程中称为嵌套。
任意数量的这些语句可以相互嵌套。缩进是确定嵌套级别的唯一方法。它们可能会令人困惑,因此除非必要,否则必须避免它们。

Python 嵌套 if 示例

‘’’In this program, we input a number check if the number is positive or negative or zero and display an appropriate message This time we use nested if statement’’’ num = float(input(“Enter a number: “)) if num >= 0: if num == 0: print(“Zero”) else: print(“Positive number”) else: print(“Negative number”)
输出 1
输入数字:5 正数
输出 2
输入一个数字:-1 负数
输出 3
输入一个数字:0 零

  1. 下一个教程:[Python for 循环](https://www.yuque.com/aifanj/odpp1n/cl4y34)