if 语句处理列表 Fri

5.4 if语句处理列表

favorite_fruits=['apple','banana','orange']
for fruit in favorite_fruits:
    print(f"{fruit}!")
print("that all.")
#输出
apple!
banana!
orange!
that all.

5.4.1 检查特殊元素

for循环中添加if语句来处理列表中的特殊元素。

favorite_fruits=['apple','banana','orange']
for fruit in favorite_fruits:
    if fruit=='banana':
        print("i don't like banana")
    else:
        print(f"{fruit}!")
print("that all.")
#输出
apple!
i don't like banana
orange!
that all.

5.4.2 确定列表不是空的

favorite_fruits=[]
if favorite_fruits:
  for fruit in favorite_fruits:
    print(f"{fruit}!")
else:
    print("it's empty")
print("that all.")
#输出
it's empty
that all.

将列表名作为条件表达式时,列表不为空则结果为True,为空则False。

5.4.3 使用多个列表

food=['cake','egg','apple','orange']
favorite_fruits=['apple','banana','orange']
for fruit in favorite_fruits:#遍历列表2
    if fruit not in food:#如果列表2的元素在列表1中不存在则输出
       print(f"there is no {fruit} !")
    else:
       print(f"it's {fruit}")
print("that all.")
#输出
it's apple
there is no banana !
it's orange
that all.

5-8

users=['cake','egg','apple','orange','admin']
for user in users:
    if user =='admin':
       print(f"Hello {user},would you like to see a status report? !")
    else:
       print(f"Hello {user},thank you for logging again.")
#输出
Hello cake,thank you for logging again.
Hello egg,thank you for logging again.
Hello apple,thank you for logging again.
Hello orange,thank you for logging again.
Hello admin,would you like to see a status report? !

5-9

users=[]
if users:
    for user in users:
      if user =='admin':
         print(f"Hello {user},would you like to see a status report? !")
      else:
         print(f"Hello {user},thank you for logging again.")
else:
    print("We need to find some users!")
#输出
We need to find some users!

5-10

c_users=['z','x','c','v','B']#表1
n_users=['a','x','d','g','b']#表2
c_usersed=[i.lower() for i in c_users]#表3 表1的每个元素以小写形式存入表3
for i in c_usersed:#输出表3
    print(i)
for user in n_users:
    if user in c_usersed:
        print("please enter a new name")
    else:
        print("you are only one")
#输出
z
x
c
v
b
you are only one
please enter a new name
you are only one
you are only one
please enter a new name

5.6 if语句格式

在条件表达式的书写中,需要在符号两边留出空格,不会影响代码运行,但能提高代码的阅读性。
a > 0 > a>0

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值