小白学Python笔记 Day9

本文介绍了在Python中使用if语句检查列表中的特定元素,如处理缺失的水果,并确保列表非空。此外,还涉及到多列表交互,检查用户选择的水果是否存在于系统选项中。最后提到了将列表元素转换为小写以及即将学习的字典相关内容。
摘要由CSDN通过智能技术生成

2023.5.13 Sat 今天学习if语句的剩余部分 & 字典

检查特殊元素

“如果某个值没了,如何处理” ---- for + if

如:

fruits = ['apple', 'lemon', 'orange', 'mango']
for fruit in fruits:
        print('Adding ' + fruit + '.')

print('Your fruit salad is done.')


# 如果某个水果没了,需告知客户,用if...else输出特殊提示。

fruits = ['apple', 'lemon', 'orange', 'mango']
for fruit in fruits:
        if fruit == 'lemon':
                print('Sorry, we are out of lemon right now.')
        else:
                print('Adding ' + fruit + '.')


print('Your fruit salad is done.')

确定列表非空 - 多这一步,更加严谨。-------  if 列表名: ----- 如果该列表不为空

                                                                       else            ----- 如果该列表为空

# 假设水果今天都没了,测试是否非空就很有必要。
fruits = [ ]      ---------- 空集空一格
if fruits:
        for fruit in fruits:
                print('Adding ' + fruit + '.')
else:
        print('Sorry, no more salad today.')

>>> Sorry, no more salad today.

使用多个列表

# 多个列表 - 检查所选是否在系统选项中。如:检查该新用户名是否已存在。
our_fruits = ['apple', 'lemon', 'orange', 'mango']
cus_fruits = ['cherry', 'lemon', 'orange']
for cus_fruit in cus_fruits:                  ------------- 先定义要检查的范围:在客户所说的水果里。
        if cus_fruit in our_fruits:             ------------- 再检查客户所说水果是否在店里所提供水果里。
                print('Adding ' + cus_fruit + '.')
        else:
                print("Sorry, we don't have this fruit.")

print('Ok, you salad is done!')

---------------- 做几个练习 ------------------

Note:把列表全部元素变为小写↓

列表名 = [ 元素.lower() for 元素 in 列表名]

e.g.: 

user_names = ['John', 'Cathy', 'Amy']

user_names = [user_name.lower() for user_name in user_names]

---------------- 第五章完---------------- 晚上开始学习第六章:字典--------------------加油----------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值