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]
---------------- 第五章完---------------- 晚上开始学习第六章:字典--------------------加油----------