0

So I have this function in a file test.py with the following code:

def some_function(): 
   for i in range(1, 6):
        # Create 5 variables s1, s2, etc with values 1, 2 ...
        exec("s{} = i".format(i, i))
   print(s1)

But it gives me the error message:

  File "/some_directory/test.py", line 5, in test
    print(s1)
NameError: name 's1' is not defined

When I run the same code in the interpreter console, however, there is no error whatsoever, and all the variables s1, s2, s3.. are defined.

Why does the code not work when it's encapsulated?

Bruno KM
  • 768
  • 10
  • 20
  • 2
    Your indentation is messed up, which could be important here. Please check it. – BrenBarn Jan 21 '17 at 22:19
  • 1
    For what reason would you possibly need to do assignments with exec? Imagine some – Natecat Jan 21 '17 at 22:20
  • better use list (or dictionary) and `s[1]` instead of `s1` - it will be more usefull. – furas Jan 21 '17 at 22:20
  • 2
    range(1,6) is practically already what you need. – Natecat Jan 21 '17 at 22:21
  • The indentation messed up when I wrote the code for stackoverflow, it's correct in the file. I fixed it in the question now as well. – Bruno KM Jan 21 '17 at 22:24
  • This is almost certainly due to a difference in treating local variables in the `exec()` function in python 2 vs 3. – Grisha Levit Jan 21 '17 at 22:25
  • Grisha could you elaborate? – Bruno KM Jan 21 '17 at 22:28
  • if you really need to use exec, you have to be careful what context you use. Try to replace your `exec` statement with `exec("s{} = {}".format(i, i), globals())`. That should do it. However, usually there are better solutions than using exec() - using a list would be better in your example, as already commented above. – Andi Kleve Jan 21 '17 at 22:31

0 Answers0