python if语句 5

1.条件测试

cars = ['audi', 'bmw', 'subaru', 'toyota'] 

for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())

#下面检查不相等  !=
top='mus'
if top!='ac':
    print(top)

#使用and 检查多个条件
age,score=20,80
if age>18 and score>70:
    print(f"{age},{score}")

#使用or 检查多个条件
if age>18 or score>90:
    print(f"{age},{score}")

# 检查列表中是否包含
banned=['andrew','carolina','david']
user='marie'
if user in banned:
    print(f"存在{user}")
if user not in banned:
    print(f"不存在{user}")

#布尔表达式
game_active=True
can_edit=False
if game_active:
    print ("激活游戏")

 2. if 语句

# if elif else
age=12
if age<4:
    print('your admission cost is $0')
elif age<18:
    print('your admission cost is $25')
elif age<20:
    print('your admission cost is $30')
else:
    print('your admission cost is $40')

#测试多个条件
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print("adding mushrooms")
if 'extra cheese' in requested_toppings:
    print("adding extra cheese")
if 'm' in requested_toppings:
    print ("adding m")

 3.使用if语句处理列表

#确定列表不是空的
requested_toppings=[]

if requested_toppings:
    for requested_topping in requested_toppings:
        print(requested_topping)
else:
    print ("list is empty")

#使用多个列表, 获取requestes元素存在于avaliables中的
avaliables=['mushrooms', 'olives', 'green peppers',
                        'pepperoni', 'pineapple', 'extra cheese']
requestes= ['mushrooms', 'french fries', 'extra cheese']

for  avaliable in avaliables:
    if avaliable in requestes:
        print(f"adding {avaliable}")
    else:
        print(f"we don't have {avaliable}")

 

posted on 2022-12-26 12:25  花阴偷移  阅读(5)  评论(0编辑  收藏  举报

导航