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


0 votes
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:

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

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

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:

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:

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