Zak Ray Sick
Zak Ray Sick

Reputation: 95

Python: Using variables in function call

Looking to use variables defined earlier in the code when calling a function later in the code.

variable = 'a'
results = variable_func()

The user has the ability to specify 'variable' in my example. Depending on what the choose, the function will be slightly different. Therefore, I want to be to use the variable when I call the function instead of having to use a bunch of different if then statements.

Is this possible?

Upvotes: 0

Views: 54

Answers (1)

brunns
brunns

Reputation: 2764

Assuming you want to call a different function depending on what variable is set to, the normal approach looks like:

functions = {'a': variable_func, 'b': another_variable_func} # etc.

variable = 'a'
results = functions[variable]()

Upvotes: 2

Related Questions