Python教程-2.1节:Python if … else语句

在本文中,您将学习使用不同形式的if..else语句在Python程序中创建决策。

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

仅当满足特定条件时,才需要执行代码时才需要决策。

if…elif…else语句在Python中用于决策。

Python if语句语法

if test expression:
    statement(s)

在这里,test expression仅当文本表达式为时,程序才会评估并执行语句True

如果文本表达式为False,则不执行该语句。

在Python中,if语句的主体由缩进指示。主体以缩进开始,第一条未缩进的线标记结束。

Python将非零值解释为TrueNone并且0被解释为False

Python if语句流程图

Python编程中if语句的流程图
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 expressionif仅在测试条件为时才执行主体True

如果条件为Falseelse则执行的主体。缩进用于分隔块。

Python if..else流程图

Python编程中if ... 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将执行bodyof的主体,而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的流程图

Python编程中if ... elif .... else的流程图
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")

运行代码

当变量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
0