python——第五章 if语句

一个简单示例 

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!")		
	

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值