如果我们在代码中需要检查多个条件语句,此时我们可以使用 all() 或 any() 函数来实现我们的目标。
一般来说, 当我们有多个 and 条件时使用 all() ,当我们有多个 or 条件时使用 any() 。这种用法将使我们的代码更加清晰易读,可以方便我们在调试时不会遇到麻烦。
1.all() 函数
对于 all() 的一般例子如下:
size = "lg"
color = "blue"
price = 50
# bad practice
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to but the product.")
更好的处理方法如下:
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if all(conditions):
print("Yes, I want to but the product.")
2. any() 函数
对于 any() 的一般例子如下:
# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to but the product.")
更好的处理方法如下:
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if any(conditions):
print("Yes, I want to but the product.")
好了,今天的分享就到这里,希望对大家有所帮助。
对于Python有兴趣想一起交流的,都可以加下微信,在这里我也准备了一份学习资料送给大家,主要包含爬虫入门(爬虫工作流程 http工作流程)、逆向工程、逆向算法、异步爬虫、安卓逆向这几个板块,适合Python入门的朋友学习,都是精华,快来白嫖!