一个简单示例
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
if-elif-else 结构
例如,来看一个根据年龄段收费的游乐场:
age=12
if age<4:
print("Your admission cost is $0")
elif age<18:
print("Your admission cost is $5")
else :
print("Your admission cost is $10")
或者
age=12
if age<4:
price=0
elif age<18:
price=5
else :
price=10
print("Your assignment cost is $ "+str(price)+".")
测试多个条件
下面再来看前面的比萨店示例。如果顾客点了两种配料,就需要确保在其比萨中包含这些配料:
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushroom")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese")
print("\nFinishing making your pizza!")
总之,如果你只想执行一个代码块,就使用if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的if 语句。
使用if 语句处理列表
requested_toppings=['mushrooms','extra cheese','green peppers']
for requested_topping in requested_toppings:
if requested_topping=='green peppers':
print("Sorry,we are out of green peppers right now")
else:
print("Adding "+requested_topping+".")
print("\nFinishing making your pizza!")
确定列表不是空的
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping=='green peppers':
print("Sorry,we are out of green peppers right now")
else:
print("Adding "+requested_topping+".")
print("\nFinishing making your pizza!")
else:
print("Are you sure you want a plain pizza!")
使用多个列表
#定义列表:顾客点的配料
requested_toppings=['mushrooms', 'french fries', 'extra cheese']
#定义列表:餐厅提供的配料
available_toppings=['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
#判断列表是否为空,若不为空
if requested_toppings:
#使用for循环遍历整个列表
for requested_topping in requested_toppings:
#判断顾客点的配料餐厅是否提供
if requested_topping not in available_toppings:
print("Sorry,we don't have "+requested_topping+".")
else:
print("Adding "+requested_topping+".")
print("\nFinishing making your pizza!")
#若列表为空
else:
print("Are you sure you want a plain pizza!")