【Python学习】第四章 if条件语句

# _*_ coding:utf-8 _*_
"""
name:zhangxingzai
date:2022/10/29
form:《Python编程从入门到实践》
"""

第四章 if条件语句

4.1 一些简单的if语句示例
cars = ['audi', 'bwm', 'subaru', 'toyota']

for car in cars:
    if car == 'bwm':
        print(car.upper())
    else:
        print(car.title())
# 这个实例中循环首先检查当前car是否为bwm,如果是,则以全部大写的方式打印,否则以首字母大写的方式打印

# 下面演示if语句如何使用不等运算符
requestde_top = 'mushrooms'
if requestde_top != 'anchvies':
    print('Hold the anchovies')

# 下面示例if语句中使用比较运算符
age = 19
if age >= 18:
    print('您已成年,可以上网了!')

# 下面示例if-else语句结构
age = 17
if age >= 18:
    print('您已成年,可以上网了!')
else:
    print('还没成年,回家喝奶吧!')
# 注意:else是和if是同一个缩进的语句块,不要缩进到if语句块内

# 下面示例if-elif-else语句结构
age = 12
if age < 4:
    print('您不需要买票0元')
elif age < 18:
    print('您的票价为半价20元')
else:
    print('您需要买成人票40元')

# 为了让代码更简洁也可以写成下面这样
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 20
else:
    price = 20
print(f'您需要花费{price}元')
"""
if-elif-else结构虽然强大,但是仍要注意,该结构仅适用于只有一个条件满足的情况。
然而有时我们不得不关注所有条件是否满足,此时就需要一个if一个去检查了。
"""

# 4.2 使用if语句处理列表
requested_tops = ['mushrooms', 'green peppers', 'extra cheese']
for requested_top in requested_tops:
    print(f'添加原料{requested_top}')
print('使用以上的原料制作披萨')

# 假如green peppers用完了,应该怎么处理呢
requested_top1s = ['mushrooms', 'green peppers', 'extra cheese']
for requested_top1 in requested_top1s:
    if requested_top1 == 'green peppers':
        print('我们没有green peppers了,需要进货')
    else:
        print(f'添加原料{requested_top1}')
print('使用以上的原料制作披萨')

# 确定列表不是空的
requested_top2s = []
if requested_top2s:
    for requested_top2 in requested_top2s:
        print(f'添加{requested_top2}')
    print('使用以上原料制作披萨')
else:
    print('询问用户是否想要一个原味披萨')

# 使用多个列表实现披萨制作辅助提示
available_tops = ['mushrooms', 'olives', 'green peppers',
                 'pepperini', 'pineapple', 'extra cheese']  # 已有材料
requested_tops = ['mushrooms', 'french fries', 'extra cheese']  # 用户点的口味
for requested_top in requested_tops:
    if requested_top in available_tops:
        print(f'添加{requested_top}')
    else:
        print(f'没有{requested_top}了,需要进货')
print('使用以上材料制作披萨')
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胖虎*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值