Python if语句
1.if-else语句
【实例】:
number = 30
if number >20:
print("bigger")
else:
print("smaller")
【运行结果】:
bigger
2.if-elif-else语句
【实例】:游乐场按年龄收取门票:4岁以下免票;4到18岁10元;18岁以上20元。
age = 12
if age < 4 :
print("免费")
elif age < 18 :
print("10元票价")
else :
print("20元票价")
【运行结果】:
10元票价
3.检查特定值是否在列表
【实例】:
countries = ['china','america','england']
if 'russia' in countries:
print("russia √")
elif 'england' in countries:
print("england √")
【运行结果】:
england √
4.例题:售卖水果
【实例】:
needs = ['apple','pear','lemon']
fruit_shops = ['apple','pear','banana']
for need in needs:
if need in fruit_shops:
print(f"It is your {need}")
else:
print(f"sorry,we don't have {need}")
【运行结果】:
It is your apple
It is your pear
sorry,we don't have lemon