Python 简明教程
Python - if Statement
Python If Statement
Python 中的 if statement 评估条件为真或假。它包含一个逻辑表达式来比较数据,并根据比较结果做出决策。
The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based on the result of the comparison.
Syntax of the if Statement
if expression:
# statement(s) to be executed
如果布尔表达式计算结果为 TRUE,则执行 if 块中的语句。如果布尔表达式计算结果为 FALSE,则执行 if 块结束后的第一组代码。
If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if block is executed.
Flow Diagram (Flowchart) of the if Statement
下图展示了 if 语句的流程图 −
The below diagram shows flowchart of the if statement −
Example of Python if Statement
我们考虑以下示例,如果客户的购买金额 > 1000,则可以享受 10% 的折扣;否则,不适用折扣。以下流程图展示了整个决策过程 −
Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process −
首先,将折扣变量设置为 0,将金额变量设置为 1200。接下来,使用一个 if 语句来检查金额是否大于 1000。如果此条件为真,则计算折扣金额。如果适用折扣,则从原始金额中减去它。
First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount.
可以将上述流程图对应的 Python 代码写成如下所示 −
Python code for the above flowchart can be written as follows −
discount = 0
amount = 1200
# Check he amount value
if amount > 1000:
discount = amount * 10 / 100
print("amount = ", amount - discount)
此处金额为 1200,因此扣除 120 的折扣。执行此代码后,你会得到以下 output −
Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output −
amount = 1080.0
将变量数量更改为 800,并再次运行代码。此时,没有任何折扣适用。你将获得以下输出 −
Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −
amount = 800