0

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?

3
  • Are you looking for something other than passing 'a' as an argument to the function call? Commented Apr 15, 2019 at 17:06
  • Or do you want to call a different function depending on what the value of variable is? Commented Apr 15, 2019 at 17:08
  • Or do you want to call a different function depending upon what variable is set to? Commented Apr 15, 2019 at 17:08

1 Answer 1

2

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]()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.