Python入门—处理多个条件语句的最佳姿势(附源码详解)

Python入门—处理多个条件语句的最佳姿势(附源码详解),第1张

如果我们在代码中需要检查多个条件语句,此时我们可以使用 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入门的朋友学习,都是精华,快来白嫖!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/789072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存