Python if语句


(1)简单的if语句

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

输出

Audi
BMW
Subaru
Toyota

(2)and or

age_0 = 22
age_1 = 24
if(age_0 >= 21 and age_1 >= 21):
    print("Yes1")
if(age_0 >= 24 or age_1 >= 24):
    print("Yes2")

输出

Yes
Yes2

(3)检查特定值是否包含在列表中

requested_toppings = ['mushrooms', 'onions', 'pineapple']
if('mushrooms' in requested_toppings):
    print("包含1")
if('pepperoni' in requested_toppings):
    print("包含2")

输出

包含1

(4)检查特定值是否不包含在列表中

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")

输出

Marie, you can post a response if you wish.

(5)布尔表达式

game_active = True
can_edit = False

(6)if-elif-else 结构

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + ".")

输出

Your admission cost is $5.

(7)测试多个条件

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

输出

Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

(8)确定列表不是空的

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

输出

Are you sure you want a plain pizza?

(9)使用多个列表

available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + ".")
    else:
        print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")

输出

Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值