0

I have a problem which I simplified as follows:

def func_1(): # Define first function
  a = 1
  return a

print(func_1()) # Call first function

def func_2(): # Define second function
  a = 2
  return a

print(func_2()) # Call second function

. . . . .

def func_400(): # Define four-hundredth function
  a = 400
  return a

print(func_400()) # Call four-hundredth function

As you can see, I need to define and call 400 functions. The actual definition and calling of the 400 functions is much more complex for my problem and needing to define and call 400 functions will be too cumbersome. Is there any way this can formulated as a loop. Just to confirm, all function names should be different. Do we have something in python similar to this :

for i in range(400):
  def func_(i+1)():
    a = i+1
    return a
  print(func_(i+1))
  
Buna
  • 45
  • 4

1 Answers1

0

It is better to define only a few functions, pass the number as argument and then decide which code to run. But, following your general idea, use exec to send a string as python code to run:

for i in range(400):
    python_code = """
        def func_""" + (i+1) +  """():
            a = """ + (i+1) +  """
            return a
        print(func_""" + (i+1) +  """())
    """
    exec(python_code)
Eduardo Poço
  • 2,819
  • 1
  • 19
  • 27