Python if-else 语句



Python if else 语句

Python 中,if-else 语句用于在if 语句中的条件为真时执行一段代码,而在条件为假时执行另一段代码。

if-else 语句的语法

Python 中 if-else 语句的语法如下:

if boolean_expression:
  # code block to be executed
  # when boolean_expression is true
else:
  # code block to be executed
  # when boolean_expression is false

如果布尔表达式计算结果为 TRUE,则将执行if 块内的语句;否则,将执行else 块内的语句。

if-else 语句的流程图

此流程图显示了如何使用 if-else 语句:

ifelse syntax

如果expr 为 True,则执行 stmt1、2、3 块,然后默认流程继续执行 stmt7。但是,如果expr 为 False,则执行 stmt4、5、6 块,然后继续默认流程。

上述流程图的 Python 实现如下:

if expr==True:
   stmt1
   stmt2
   stmt3
else:
   stmt4
   stmt5
   stmt6
Stmt7

Python if-else 语句示例

让我们通过以下示例了解 if-else 语句的用法。在此,变量 age 可以取不同的值。如果表达式 age > 18 为真,则将显示 有投票资格 消息;否则,将显示 无投票资格 消息。下面的流程图说明了此逻辑:

if-else

现在,让我们看看上述流程图的 Python 实现。

age=25
print ("age: ", age)
if age >=18:
   print ("eligible to vote")
else:
   print ("not eligible to vote")

执行此代码后,您将获得以下输出

age: 25
eligible to vote

要测试else 块,请将age 更改为 12,然后再次运行代码。

age: 12
not eligible to vote

Python if elif else 语句

if elif else 语句允许您检查多个表达式的真假,并在其中一个条件计算结果为 TRUE 时执行一段代码。

else 块类似,elif 块也是可选的。但是,程序只能包含一个else 块,而可以在if 块之后包含任意数量的elif 块

Python if elif else 语句的语法

if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)

if elif else 如何工作?

关键字elifelse if的简写形式。它允许逻辑以elif语句的级联方式排列在第一个if语句之后。如果第一个if语句计算结果为假,则后续的elif语句将逐个评估,如果任何一个语句满足条件,则退出级联。

级联中的最后一个是else块,当所有前面的if/elif条件都失败时,它将被执行。

示例

假设购买商品有不同的折扣额度:

  • 金额超过10000元,折扣20%;

  • 金额在5000-10000元之间,折扣10%;

  • 金额在1000-5000元之间,折扣5%;

  • 金额小于1000元,无折扣。

下图是这些条件的流程图。(此处应插入流程图)

if-elif

我们可以使用if-else语句编写上述逻辑的Python代码:

amount = 2500
print('Amount = ',amount)
if amount > 10000:
   discount = amount * 20 / 100
else:
   if amount > 5000:
      discount = amount * 10 / 100
   else:
      if amount > 1000:
         discount = amount * 5 / 100
      else:
         discount = 0

print('Payable amount = ',amount - discount)

设置amount变量来测试所有可能的条件:800、2500、7500和15000。输出将相应变化。

Amount: 800
Payable amount = 800
Amount: 2500
Payable amount = 2375.0
Amount: 7500
Payable amount = 6750.0
Amount: 15000
Payable amount = 12000.0

虽然这段代码可以完美运行,但是如果仔细观察每个if和else语句递增的缩进级别,如果还有更多条件,将会难以管理。

Python if elif else语句示例

elif语句使代码更易于阅读和理解。以下是使用if elif else语句实现相同逻辑的Python代码:(此处应插入代码)

amount = 2500
print('Amount = ',amount)
if amount > 10000:
   discount = amount * 20 / 100
elif amount > 5000:
   discount = amount * 10 / 100
elif amount > 1000:
   discount = amount * 5 / 100
else:
   discount=0

print('Payable amount = ',amount - discount)

上述代码的输出如下:(此处应插入输出)

Amount: 2500
Payable amount = 2375.0
广告
© . All rights reserved.