在本文中,您将学习使用不同形式的if..else语句在Python程序中创建决策。
if … else语句在Python中是什么?
仅当满足特定条件时,才需要执行代码时才需要决策。
该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语句
# 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 is a positive number This is always printed This 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 if else: Body of else
该if..else
语句评估test expression
并if
仅在测试条件为时才执行主体True
。
如果条件为False
,else
则执行的主体。缩进用于分隔块。
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")
运行代码
输出量
Positive or Zero
在上面的例子中,当NUM等于3,测试表达式为真和的主体if
被执行并且body
的否则跳过。
如果num等于-5,则测试表达式为false,else
执行的主体,if
并且跳过的主体。
如果num等于0,则测试表达式为true,if
将执行body
of的主体,而else的主体将被跳过。
Python if … elif … else语句
if … elif … else的语法
if test expression: Body of if elif test expression: Body of elif else: Body of else
的elif
是短期的,如果别的。它允许我们检查多个表达式。
如果该条件if
就是False
,它检查下一个的条件elif
的块等。
如果所有条件都为False
,则执行else的主体。
if...elif...else
根据条件,在几个块中仅执行一个块。
该if
块只能有一个else
块。但是它可以有多个elif
块。
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")
运行代码
当变量num为正时,正数 打印。
如果num等于0,零 打印。
如果num为负数,负数 打印。
Python嵌套if语句
我们可以if...elif...else
在另一个if...elif...else
语句中包含一个语句。这在计算机编程中称为嵌套。
这些语句中的任何数目都可以彼此嵌套。缩进是弄清楚嵌套级别的唯一方法。它们可能会造成混淆,因此除非有必要,否则必须避免使用它们。
如果示例嵌套Python
'''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
Enter a number: 5 Positive number
输出2
Enter a number: -1 Negative number
输出3
Enter a number: 0 Zero