# _*_ 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('使用以上材料制作披萨')
【Python学习】第四章 if条件语句
于 2022-10-29 22:29:24 首次发布