三、if语句

3.1 一个简单实例 

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw': 
        pirnt(car.upper())
    else:
        pirnt(car.title())

Audi    BMW    Subaru    Toyota

3.2  条件测试(True  False)

① 检查是否相等时忽略大小写

car = 'Audi'
car == 'audi' #False

car = 'Audi'
car.lower() == 'audi' #True

② 检查是否不相等

判断不相等可结合使用!=

requested_topping = 'anchovies'
if requested_topping != 'anchovies': #不要忘了冒号
    pirnt("Hold the anchovis!")

③ 检查多个条件(and,or)

④ 检查特定值是否包含在列表中

requested_topping = ['mushroos','onions','pineapple']
'mushrooms' in requested_toppings

#True

⑤ 检查特定值是否不包含在列表中

banned_users = ['andrew','carolian','david']
user = 'marie'

if user not in banned_users:
    print(f"{user.title()},you can post a response if you wish.")
    
#Marie,you can post a response if you wish.

3.3 if 语句

① if--else结构

if 条件测试结果为True:#不要忘了冒号
   执行xxx操作
else:#不要忘了冒号
   执行xxx操作(如果上面if测试没有通过的话)

② if--elif--else结构

if 条件测试结果为True:
   执行xxx操作
elif:
   执行xxx操作
else:
   执行xxx操作

3.4 用 if 语句处理列表

① 检查特殊元素

# 披萨配料:mushrooms,green peppers,extra cheese
# 使用for循环告诉用户需要陆续添加到披萨的三种配料才能完成制作
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print(f"Adding{requested_topping}.")
print("\nFinsihed making your pizza!")

# 青椒用完了,告诉用户不能添加青椒的原因。
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry,we are out of green peppers right now.")
    else:
        print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")

② 确定列表不是空的

# 制作披萨前检查顾客点的配料表是否为空。
# 为空,就像顾客确认是否要点原味披萨
# 不为空,就向前面示例那样制作披萨
requested_topping = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding{requested_topping}.")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")
        

 

 
posted @ 2024-07-03 16:24  鹤比纷恆红  阅读(65)  评论(0)    收藏  举报