原文: https://www.programiz.com/python-programming/if-elif-else
在本文中,您将学习使用不同形式的if..else语句在 Python 程序中创建决策。
Python 中的if...else语句是什么?
仅当满足特定条件时,我们才想执行代码时才需要决策。
if…elif…else语句在 Python 中用于决策。
Python if语句语法
if test expression:statement(s)
在此,程序将求值test expression并仅在测试表达式为True时才执行语句。
如果测试表达式为False,则不执行该语句。
在 Python 中,if语句的主体由缩进指示。 主体以缩进开始,第一条未缩进的线标记结束。
Python 将非零值解释为True。None和0解释为False。
Python if语句流程图

Python 编程中if语句的流程图
示例:Python if语句
# If the number is positive, we print an appropriate messagenum = 3if num > 0:print(num, "is a positive number.")print("This is always printed.")num = -1if num > 0:print(num, "is a positive number.")print("This is also always printed.")
运行该程序时,输出为:
3 is a positive numberThis is always printedThis is also always printed.
在上面的示例中,num > 0是测试表达式。
仅当if的主体的值为True时,才执行它。
当变量num等于 3 时,测试表达式为true,并且执行if主体内的语句。
如果变量num等于 -1,则测试表达式为false,并且跳过if主体内部的语句。
print()语句位于if块之外(未缩进)。 因此,无论测试表达式如何,都将执行它。
Python if...else语句
if...else的语法
if test expression:Body of ifelse:Body of else
if..else语句求值test expression并仅在测试条件为True时才执行if的主体。
如果条件为False,则执行else的主体。 缩进用于分隔块。
Python if..else流程图

Python 中if...else语句的流程图
if...else的示例
# Program checks if the number is positive or negative# And displays an appropriate messagenum = 3# Try these two variations as well.# num = -5# num = 0if num >= 0:print("Positive or Zero")else:print("Negative number")
输出
Positive or Zero
在上面的示例中,当num等于 3 时,测试表达式为true,并且执行if的主体,其他的body被跳过。
如果num等于 -5,则测试表达式为false,并且执行else的主体,并且跳过if的主体。
如果num等于 0,则测试表达式为true,并且执行if的主体,而跳过其他的body。
Python if...elif...else语句
if...elif...else的语法
if test expression:Body of ifelif test expression:Body of elifelse:Body of else
elif是if的缩写。 它允许我们检查多个表达式。
如果if的条件为False,它将检查下一个elif块的条件,依此类推。
如果所有条件均为False,则执行else的主体。
根据条件,仅执行几个if...elif...else块中的一个块。
if块只能有一个else块。 但是它可以具有多个elif块。
if...elif...else的流程图

Python 中if...elif....else语句的流程图
if...elif...else的示例
'''In this program,we check if the number is positive ornegative or zero anddisplay an appropriate message'''num = 3.4# Try these two variations as well:# num = 0# num = -4.5if num > 0:print("Positive number")elif num == 0:print("Zero")else:print("Negative number")
当变量num为正时,将打印正数。
如果num等于 0,则打印零。
如果number为负,则打印负数。
Python 嵌套if语句
我们可以在另一个if...elif...else语句中包含一个if...elif...else语句。 这在计算机编程中称为嵌套。
这些语句中的任何数目都可以彼此嵌套。 缩进是弄清楚嵌套级别的唯一方法。 它们可能会造成混淆,因此除非有必要,否则必须避免使用它们。
Python 嵌套if示例
'''In this program, we input a numbercheck if the number is positive ornegative or zero and displayan appropriate messageThis 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
Enter a number: 5Positive number
输出 2
Enter a number: -1Negative number
输出 3
Enter a number: 0Zero
