0

So I have function that does some stuff that I need to run: TestRun(x)

I have an array of these that I want to run in a loop, but I need to define them such as df_(x) = TestRun(x). The actual code that I am trying to loop looks like the below:

df_0 = TestRun(0); df_1 = TestRun(1); df_2 = TestRun(2);

I have a few thousand of these and would like to make it simular but need some help to get it to work. Everything I have tried has failed thus far.

I was thinking something like this but it doesn't work:

x = 0
while x < int(5):
    temp = "df_" + str(x) = TestRun(x)
    return temp
    x += 1

It's important that the scrip actually run the function as it loops through.

  • I think what you want to do is something like this: https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string There are ways mentioned for calling class methods using string name, individual functions using string name, using dictionary function calls etc – Rusty Nov 17 '19 at 04:58
  • 1
    Why do you want a to store the result in a variable? You can always use a dictionary if you just want to save the output of the function. – Subhrajyoti Das Nov 17 '19 at 05:08
  • Did you define the `TestRun` function yourself? If so, it should be named `test_run`, no? Can you share more of your code? This is odd and a bit confusing. See: [mcve]. – AMC Nov 17 '19 at 06:08
  • _I have an array of these that I want to run in a loop..._ An array of what, exactly? – AMC Nov 17 '19 at 06:11
  • 1) In python you can't define a variable's name based on a changing variable. So you can't create a variable named `df_0` using `"df_" + str(x)`". You will need to create a `dictionary` named `"dfs"` for example, and do `dfs[x] = TestRun(x)` in the loop. 2) The moment you do `return` in a function, it ends the function, and the rest of the code (or other iterations of the loop) doesn't commit. So don't write `return` in the middle of the loop if you want the loop to continue. – Aryerez Nov 17 '19 at 06:13

1 Answers1

1

What I got from the question, it looks like you want to store the result in the dictionary with the function call (not sure why). But here how I will do it.

def testRun(x):
    return x * x


def test_caller():
    x = 0
    func_dict = {}
    while x < int(5):
        func_dict['df_'+str(x)] = testRun(x)
        x += 1
    return func_dict


print(test_caller())

Output : {'df_0': 0, 'df_1': 1, 'df_2': 4, 'df_3': 9, 'df_4': 16}

SK -
  • 459
  • 5
  • 15
  • It's a part of a step of a bigger project. I basically want it to run the function for df_0 = TestRun(0) then use a loop to run it for df_1 = TestRun(1) and on and on until a certain number of iterations. But as a part of it, it also is storing df_0 and df_1 for later use. – Andrew Hicks Nov 17 '19 at 05:52
  • @AndrewHicks In that case, couldn’t you just use a list/list comprehension? Index `0` would correspond to `df_0`, index `1` to `df_1`, etc. – AMC Nov 17 '19 at 06:10