Python if else用法
时间: 2023-10-21 21:03:05 浏览: 76
if else用法
Python中的if-else语句用于在条件为真或假时执行不同的代码块。其基本语法如下:
```
if condition:
# if block of code
else:
# else block of code
```
其中,condition是一个布尔表达式,当其为True时执行if块中的代码,否则执行else块中的代码。
示例:
```
x = 5
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
```
输出:
```
x is less than or equal to 10
```
可以使用elif关键字来添加更多的条件判断。示例:
```
x = 5
if x > 10:
print("x is greater than 10")
elif x < 5:
print("x is less than 5")
else:
print("x is between 5 and 10")
```
输出:
```
x is between 5 and 10
```
阅读全文