首页 > 解决方案 > Writing optimized multiple conditional statements Or use any other way to check condition? in python

问题描述

What is the optimized way to write below conditional statements, i wanted to avoid the multiple if-elif statements

def test(val):
     return False if val is 0 else True

def test_func(x=None, y=None):
    if(x == "check" and y == "1" and test(0) == False):
        print("Option 1")
    elif(x == "check" and y == "2" and test(0) == False):
        print("Option 2")
    elif(x == "uncheck" and y == "1" and test(1) == True):
        print("Option 3")
    elif(x == "uncheck" and y == "2" and test(1) == True):
        print("Option 4")

标签: python-3.x

解决方案


我做了这个:

if x == "check" and test(0) == False:
    if y == "1":
        print("Option 1")
    else:
        print("Option 2")
elif x == "uncheck" and test(1) == true:
    if y == "1":
        print("Option 3")
    else:
        print("Option 4")

我不知道它是否有帮助,因为它没有缩短(如果没有,请给我更多关于您尝试做什么的背景信息,以便我可以尝试不同的方法),但我无法对其进行更多优化。希望这可以帮助。

-JLT


推荐阅读