elif是python中的一个关键字(区分大小写),在条件语句中使用,如果我们要检查多个条件,则必须使用elif关键字检查下一个条件。
注意:第一个条件用if关键字检查,其他所有条件用elif关键字检查,最后/默认块(如果任何条件不成立)是否用else关键字写。
elif关键字的语法
if test_condition1: statement(s)-true-1 elif test_condition2: statement(s)-true-2 . . .. else: statement(s)-false
在这里,如果test_condition1为True,则 statement(s)-true-1将被执行,如果test_condition2为True,则 statement(s)-true-2将被执行,依此类推...我们可以测试多个条件,如果所有条件都不为True,则else块(statement(s)-false)将被执行。
示例
Input: num = -21 # 条件 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
示例1:输入一个数字并检查它是正数,负数还是零。
# python代码演示示例 # if,else和elif关键字 # 输入数字并检查是否 # 它是正数,负数或零。 # 输入 num = int(input("Enter a number: ")) # 条件s if num>0: print(num," is a positive value") elif num<0: print(num," is a negative value") else: print(num," is a zero")
输出结果
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
示例2:输入三个数字并找到最大的数字。
# python代码演示示例 # if,else和elif关键字 # 输入 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 # 条件s if a>b and a<c: large = a; elif b>a and b>c: large = b; else: large = c; # 打印最大数量 print("largest number is: ", large)
输出结果
Enter first number :10 Enter second number:30 Enter third number :20 largest number is: 30