Decision making one of the fundamentals operations in programming languages and applications. We mostly use decisions to implements applications logic. The primary mechanism for decisions in Python is if..elif..else
keywords. We can simple call them if-else
. In this tutorial we will look different aspects and usage examples of if-else
.
决策是编程语言和应用程序中的基本操作之一。 我们主要使用决策来实现应用程序逻辑。 Python中决策的主要机制是if..elif..else
关键字。 我们可以简单地将它们称为if-else
。 在本教程中,我们将研究if-else
不同方面和用法示例。
如果 (If)
If
is used to check whether given condition is true and run some code. So we need some condition and some code block. The syntax of if is like below.
If
用于检查给定条件是否为真并运行一些代码。 因此,我们需要一些条件和一些代码块。 if的语法如下。
if CONDITION
CODE_BLOCK
Now we can understand if with an example better. In this example we check if 0 is less than 10 .
现在我们可以用一个例子更好地了解。 在此示例中,我们检查0是否小于10。
if( 0 < 10 ):
print("0 is less than 10")
Because given condition returned True
the code block executed and printed.
因为给定条件返回True
所以代码块被执行并打印。
If-Elif (If-Elif)
If we want to check multiple conditions in a single step and run code block accordingly we can use If-Elif
statement. We can provide multiple conditions like below.
如果我们要在一个步骤中检查多个条件并相应地运行代码块,则可以使用If-Elif
语句。 我们可以提供如下多个条件。
if CONDITION:
CODE_BLOCK
elif CONDITION:
CODE_BLOCK
...
elif CONDITION:
CODE_BLOCK
We can understand if-elif with an example where we check 3 conditions.
我们可以通过检查3个条件的示例来了解if-elif。
a= 7
if ( a > 10 ):
print("$a is greater than 10")
elif (a > 0):
print("$a is between 10 and 0")
elif (a <0):
print("$a is lower than 0")
First elif is executed and related text printed.
执行第一个elif并打印相关文本。
If-Elif-Else (If-Elif-Else)
As we have seen previous parts we can define limitless conditions and code blocks. There is a special conditions which is triggered when none of the previous conditions are met. We call this as else
and put at the end of the if-elif
code block. Else
do not need any specific condition.
如前所述,我们可以定义无限条件和代码块。 当不满足任何先前条件时会触发一个特殊条件。 我们以else
调用它,并将其放在if-elif
代码块的末尾。 Else
不需要任何特定条件。
In this example we can guess the given number with else
.
在这个例子中,我们可以用else
猜出给定的数字。
a= -7
if ( a > 10 ):
print("$a is greater than 10")
elif (a >= 0):
print("$a is between 10 and 0")
else:
print("$a is lower than 0")
提供多种条件 (Providing Multiple Conditions)
Up to now we have defined single conditions in order to check. We can also use complex or multiple conditions in a single keyword. We generally use ( )
to group multiple or complex conditions. All inner conditions are computed and at the end single boolean value true or false returned.
到目前为止,我们已经定义了单个条件以进行检查。 我们还可以在单个关键字中使用复杂或多个条件。 我们通常使用( )
将多个或复杂条件分组。 计算所有内部条件,最后返回单个布尔值true或false。
(1 < 10 and 10 > 1)
(1 < 10 and 10 != 10)
(1 < 10 or 10 != 10)
翻译自: https://www.poftut.com/python-elif-else-statements-conditionals/