python学习5、if语句

# if语句——检测条件
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
# 注意使用if语句的格式和测试条件————即条件表达式
# 相等运算符在它两边的值相等时返回TRUE,否则返回false
# 检查是否不等————不等运算符!= ———如果相等返回False,不等返回TRUE
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchoviess!")
# 检测不相等的效率比相等的效率高
# 数值比较——条件语句包含多种数学比较:大于、小于、小于等于、大于等于
age = 45
if age == 45:
    print("old")
if age > 45:
    print("older")
if age < 45:
    print("yonge")
# 检测多个条件时可以使用and逻辑与和or逻辑或运算————建议两侧都加上括号,更好判断
if (age == 45) and (age > 45):
    print("old")
if (age < 45) and (age < 40):
    print("yonge")
# 检测特定值是否在列表中————in关键字————在列表中返回true,否则返回false
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
    print("yes!")
# 检测特定值是否不在列表中————not in关键字——如果不在列表中返回true,在就返回false
if 'pepperoni' not in requested_toppings:
    print("yes")
# 布尔表达式————条件测试的别名————结果要么为TRUE,要么为FALSE
geme_active = True
can_edit = False
# if——else——else语句
if age < 4:
    price = 0
elif age < 18:
    price = 25
else:
    price = 40
# 其中elif语句后面接着的时测试语句——可以连续使用多个elif语句
# python并不要求if——elif结构后面必须有else代码块
# 总之,如果想运行一个代码块,就使用if——else——else语句;如果要运行多个代码块,就是用一系列独立的if语句
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("forry,we are out of green peppers right now.")
    else:
        print(f"adding{requested_topping}")
# 利用for循环和if结合判断——注意格式
requested_topping = []
if requested_topping:
    for requested_topping1 in requested_topping:
        print(f"adding{requested_topping1}.")
    print("\nfinished making your pizza!")
else:
    print("are you sure you want a plain pizza?")
# 在python中列表为空则为false,至少包含一个元素就返回true
# 使用多个列表

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值