python中if 和elif语法使用
时间: 2023-08-21 18:10:16 浏览: 43
if和elif是Python中用于控制程序流程的条件语句。
if用于判断一个条件是否成立,如果条件成立则执行if语句块中的代码;如果条件不成立,则跳过if语句块。
语法:
```
if condition:
# code to be executed if condition is True
```
例如:
```
x = 5
if x > 0:
print("x is positive")
```
elif用于当if语句的条件不成立时,再判断一个新的条件是否成立,如果新的条件成立则执行elif语句块中的代码;如果新的条件也不成立,则跳过elif语句块。
语法:
```
if condition1:
# code to be executed if condition1 is True
elif condition2:
# code to be executed if condition2 is True and condition1 is False
```
例如:
```
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
```
注意,elif是可选的,可以有多个elif,也可以没有。
完整的if-elif语法如下:
```
if condition1:
# code to be executed if condition1 is True
elif condition2:
# code to be executed if condition2 is True and condition1 is False
elif condition3:
# code to be executed if condition3 is True and condition1 and condition2 are False
else:
# code to be executed if none of the conditions are True
```
其中else语句是可选的,用于当所有条件都不成立时执行的代码块。