0

What is the workaround for "Unexpected Indent" error from this?

In [15]: def f(x): 
    ...:     return x 
    ...:                                                                                                                                                        

In [16]: for i in range (10): 
    ...:     exec(f""" 
    ...:     v_{i} = f(i) 
    ...:     """) 
Y Bai
  • 88
  • 6
  • You're putting spaces at the beginning of the `v_` line. Since it's not inside a loop in the `exec()` function, it shouldn't be indented. – Barmar Feb 16 '23 at 23:04
  • 1
    Also, don't do this. Use a dictionary. See https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – Samwise Feb 16 '23 at 23:21

3 Answers3

1

Don't indent the line with the v_{i} assignment.

In [16]: for i in range (10): 
    ...:     exec(f""" 
    ...: v_{i} = f(i) 
    ...:     """) 

The code executed by exec() doesn't inherit the indentation of the calling code. So that statement needs to be at the beginning of the line since you're not execing a loop.

There isn't really a need for a multi-line string in the first place, you can just do:

exec(f'v_{i} = f(i)')

Of course, this whole thing is misguided. Dynamic variable names are generally a bad idea, you should be using a list or dictionary.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can fix the indentation error by rewriting the parameter of the exec function you call to span only one line instead of multiple.

quipple
  • 11
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – xlmaster Feb 21 '23 at 05:33
0

Looks like you are using execto creating 10 variables and assigning the values of f(0) to f(9).

The exec block needs to be indented one level to the right, relative to the for loop.

def f(x):
    return x

for i in range(10):
    exec(f"""
v_{i} = f(i)
""")
dhee u
  • 1
  • 3