# Python中 if 语句及其使用

9 篇文章 20 订阅

## 一、 条件测试

### 1.比较字符串相等或不相等

fruit = 'apple'
print('1.' + str(fruit == 'apple')) #判断是否相等
print('2.' + str(fruit == 'banana'))
print('3.' + str(fruit != 'apple')) #判断是否不相等
print('4.' + str(fruit != 'banana'))


### 2.比较数字

num1 = 20
num2 = 30
print('1.' + str(num1 == num2))
print('2.' + str(num1 != num2))
print('3.' + str(num1 >= num2))
print('4.' + str(num1 <= num2))


### 3.检查多个条件

num1 = 20
num2 = 30
print('1.' + str(num1 >= 15 and num2 >= 15))
print('2.' + str(num1 >= 25 and num2 >= 25))
print('3.' + str(num1 >= 25 or num2 >= 25))
print('4.' + str(num1 >= 35 or num2 >= 35))


### 4.检查特定值是否在列表中

fruits = ['grape', 'apple', 'banana', 'orange', 'pear']
print('1.' + str('apple' in fruits))
print('2.' + str('mango' in fruits))
print('3.' + str('banana' not in fruits))
print('4.' + str('watermelon' not in fruits))


## 二、if 语句

### 1.简单的if语句

num = 25
if num >= 20:
print('The number is over '+str(num)+'.')
if num < 20:
print('The number is under ' + str(num) + '.')


if语句和for循环类似，在if语句中需要执行的代码要进行缩进。

### 2. if-else 语句

num = 25
if num >= 20:
print('The number is over '+str(num)+'.')
else:
print('The number is under ' + str(num) + '.')


### 3. if-elif-else 语句

age = 13
if age <= 3:
print('The age under 3 is free.')
elif age <= 12:
print('The age between 3 and 12 is half price.')
else:
print('The age over 12 is full price.')


## 三、使用 if 语句处理列表

### 1.使用 if 语句检查列表中的特殊元素

fruits = ['grapes', 'apples', 'bananas', 'oranges', 'pears']
for fruit in fruits:
if fruit == 'apples':
print('Sorry, we are out of apples right now.')
else:
print(fruit.title() + ' are available.')


### 2.检查列表是否为空

fruits = []
if fruits:
for fruit in fruits:
if fruit == 'apples':
print('Sorry, we are out of apples right now.')
else:
print(fruit.title() + ' are available.')
else:
print('The list is empty.')


### 3.使用多个列表

fruits_available = ['grapes', 'apples', 'bananas', 'oranges', 'pears']
fruits_want = ['mangoes', 'apples', 'bananas', 'watermelons', 'pears']
for fruit in fruits_want:
if fruit in fruits_available:
print('We have ' + fruit +'.')
else:
print("Sorry, we don't have " + fruit +'.')
print('Check complete!')


## 总结

• 99
点赞
• 386
收藏
觉得还不错? 一键收藏
• 打赏
• 7
评论
04-28 196
02-28 2533
06-06 4139
04-06 5万+
11-18 7926
01-22 1075
10-10 3018
01-24 4万+
04-05 4732

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。