Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

Python: Change recurrent if statement for a function or an alternative

I am using a recurrent if statement for multiple variables, all of them are following the same condition, BUT! very important, all of them are independent, also the functions asociated to the variables are. Sometimes you execute only one function, sometimes another, sometimes all of them.

My actual code looks something like this:

if len(variable) != 0 or variable_1 is not None:
    exec_func_1(variable_1)

if len(variable_2) != 0 or variable_2 is not None:
    exec_func_2(variable_2)

if len(variable_3) != 0 or variable_3 is not None:
    exec_func_3(variable_3)

I am looking to replace the if for something like a function or a simpler line of code, since it could be repeating the same thing numerous times in my code. an example would be like:

def use_condition(variable):
    # obiously doesn't work hahah
    if len(variable) != 0 or variable is not None:
        pass

Because if I change 1 parameter in my if statement it could be nice to change it in all the "if" statements at the same time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pass functions as parameters of another function like this:

def use_condition(var, func):
    if (len(var) != 0 or var is not None:
        func(var)

Which you can then just call with the variable and the execution function you want:

use_condition(variable_1, exec_func_3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...