第4节.if语句
4.1 if语句的简单示例
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
4.2 if语句
if-else语句
age=17
if age>=18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
if-elif-else结构
用于检查超过两个的情形
'''
我们以一个根据年龄收费的游乐场为例:
4岁以下免费
4~18岁收费25美元
18(含)岁以上收费40美元
'''
age=12
if age <4:
print("Your admission cost is $0")
elif age < 18: #只会执行通过测试的代码
print("Your admission cost is $25")
else:
print("Your admission cost is $40")
#现在我们将上面的代码进行简化
age =12
if age <4:
price=0
elif age <18:
price=25
else:
price=40
print(f"Your admission cost is ${price}.")
#else代码块可以省略,只要不满足if或elif的测试条件,else中的代码就会执行
#如果知道最终要测试的条件,就可以考虑用一个elif代码块代替else代码块
#if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况,遇到了通过测试的情况,剩下的代码就会跳过执行
测试多个条件
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print('Adding mushrooms.')
if 'pepperoni' in requested_toppings:
print('Adding pepperoni.')
if 'extra cheese' in requested_toppings:
print('Adding extra cheese.')
print("\nFinished making your pizza!")
#首先创建一个列表,然后依次检查某一元素是否在列表中最后输出结果
#如果只想执行一个代码块,就是用if-elif-else结构;如果要执行多个代码块,使用一系列独立的if语句
4.3使用if语句检查列表
检查特殊元素
requested_toppings=['nushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Soory we are out of green peppers!")
else:
print(f"Adding {requested_topping}")
print(f"\nFinished making your pizza!")
确定列表不是空的
运行for循环前确定列表是否为空很重要
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}")
print ("\nFinished making your piaaz!")
else:
print("Are you sure want a plain pizza?")
使用多个列表:
available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fris','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}")
else:
print(f"Sorry,we don't have {requested_topping}")
print("\nFinished making your pizza!")