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