elif python
Python Elif关键字 (Python elif keyword)
elif is a keyword (case-sensitive) in python, it is used in the conditional statement, if we have multiple conditions to be checked, we have to use elif keyword to check next condition.
elif是python中的一个关键字(区分大小写),在条件语句中使用,如果我们要检查多个条件,则必须使用elif关键字检查下一个条件。
Note: First condition is checked with if keyword and other all are checked with elif keyword and if the last/default block (if any condition is not true) is written with else keyword.
注意:第一个条件用if关键字检查,其他全部用elif关键字检查,最后/默认块(如果任何条件不成立)是否用else关键字写。
Syntax of elif keyword
elif关键字的语法
if test_condition1:
statement(s)-true-1
elif test_condition2:
statement(s)-true-2
.
.
..
else:
statement(s)-false
Here, if test_condition1 is True, then statement(s)-true-1 will be executed, if the test_condition2 is True, then statement(s)-true-2 will be executed, and so on... we can test multiple conditions, if all conditions are not True, then else block (statement(s)-false) will be executed.
在这里,如果test_condition1为True ,则将执行语句-true-1 ,如果test_condition2为True ,则将执行语句-true-2 ,依此类推...我们可以测试多个条件,如果所有条件都不都是True ,那么将执行else块( statement-s false )。
Example:
例:
Input:
num = -21
# condition
if num>0:
print(num," is a positive value")
elif num<0:
print(num," is a negative value")
else:
print(num," is a zero")
Output:
-21 is a negative value
if,else,elif关键字的Python示例 (Python examples of if, else, elif keywords)
Example 1: Input a number and check whether it is positive, negative or zero.
示例1:输入一个数字并检查它是正数,负数还是零。
# python code to demonstrate example of
# if, else and elif keywords
# Input a number and check whether
# it is positive, negative or zero.
# input
num = int(input("Enter a number: "))
# conditions
if num>0:
print(num," is a positive value")
elif num<0:
print(num," is a negative value")
else:
print(num," is a zero")
Output
输出量
First run:
Enter a number: -21
-21 is a negative value
Second run:
Enter a number: 2
2 is a positive value
Third run:
Enter a number: 0
0 is a zero
Example 2: Input three numbers and find largest number.
示例2:输入三个数字并找到最大的数字。
# python code to demonstrate example of
# if, else and elif keywords
# Input three numbers and find largest number.
a = int(input("Enter first number :"))
b = int(input("Enter second number:"))
c = int(input("Enter third number :"))
large =0
# conditions
if a>b and a<c:
large = a;
elif b>a and b>c:
large = b;
else:
large = c;
# printing largest number
print("largest number is: ", large)
Output
输出量
Enter first number :10
Enter second number:30
Enter third number :20
largest number is: 30
翻译自: https://www.includehelp.com/python/elif-keyword-with-example.aspx
elif python