目录
1. 条件测试
1.1 简单示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car.title())
1.2 检查是否相等时区分大小写
python进行字符串比较时,如果大小写不同,会被视为不同的值:
>>> car="Audi"
>>> car=="audi"
False
如果只是想比较变量的值,大小写无关紧要,可以先将变量的值转化为小写,再进行比较:
- 先用方法lower()将变量转化为小写,lower()不会修改存储在变量car中的值,然后进行比较
>>> car="Audi"
>>> car.lower()=="audi"
True
>>> print(car)
Audi
有时候检查两个值是否不相等的效率更高:
>>> request_topping = "mushroom"
>>> if request_topping != "olives":
... print("Hold!")
Hold!
2. 检查多个条件 and、or
>>> age1 = 22
>>> age2 = 18
>>> (age1 >= 21) and (age2 >= 21)
False
>>> (age1 >= 21) or (age2 >= 21)
True
2.1 检查特定值是否包含在列表中 in、not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
3. if-elif-else结构
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
因为python不要求if-elif结构后面必须有else,有些情况下,直接用elif写出特定条件准确(有时候会存在一些无效和恶意数据,如果直接用else,可能会把这些无效和恶意数据包括在else里面):
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
if-elif-else结构只适合用于只有一个条件满足的情况,当遇到了通过的测试后,python就会跳过余下的测试。
4. 使用if语句处理列表
4.1 检查特殊元素
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
#假设french fries卖完了
for topping in requested_toppings:
if topping == "french fries":
print("sorry, we are out of french fries right now.")
else:
print("adding " + topping + ".")
print("\nFinished your pizza!")
4.2 确定列表不是空的
前面我们一直假设requested_toppings是有值的,但如果用户没有order topping,requested_toppings列表为空,我们要向顾客确认他是要点普通披萨,总之就是要加一个条件确认requested_toppings列表是否为空:
在if语句中将列表名用在条件表达式中时,python将在列表至少包含一个元素时返回TRUE,并在列表为空时返回False。
requested_toppings = []
if requested_toppings:
for topping in requested_toppings:
if topping == "french fries":
print("sorry, we are out of french fries right now.")
else:
print("adding " + topping + ".")
else:
print("are you sure you want a plain pizza?")
print("\nFinished making your pizza.")
4.3 多个列表对比
如果顾客order的topping不在我们提供的topping列表中,则要输出提示:
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for topping in requested_toppings:
if topping in available_toppings:
print("Adding " + topping + ".")
else:
print("Sorry, we don't have " + topping + ".")
print("\nFinished making your pizza.")