python编程从入门到实践--第5章 if语句

一。条件测试

  符号:==, >, >=, <, <=, !=, 

       逻辑符号:and, or, not

  测试有没在列表中

复制代码
cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    if car != "subaru" and car != "toyota":
        print("German car")
        if car == "bmw":
            print(car.upper())
        else:
            print(car)
    else:
        print("Japanese car")
        if not car == "subaru":
            print("丰田")
        else:
            print("斯巴鲁")

# 测试是在列表中
requrested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requrested_toppings)

# 测试不在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(f'{user.title()}, you can post a response if you wish.')
复制代码

二。多分支

复制代码
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
elif age >= 65:
    price = 20
else:
    price = -1

print(f"Your adminssion cost is ${price}.")
复制代码

三。多条件

复制代码
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
    print('Add mushrooms.')
if 'pepperoni' in requested_toppings:
    print('Add pepperoni.')
if 'extra cheese' in requested_toppings:
    print('Adding extra cheese.')

print('\nFinished making your pizza!')
复制代码

四。处理列表

1。确定列表不为空,检查特殊元素。

复制代码
requested_toppings = ['mushrooms', 'green prppers', 'extra cheese']

# 检查列表不为空
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("\nFinished makeing your pizza!")
else:
    print("Are you sure you want a plain pizza?")
复制代码

2。使用多个列表

复制代码
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'green prppers', '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!")
复制代码

 

posted @   獨懼  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示