0

I have some strings which I want to turn into variable names and assign values to them. Here is part of the code I have:

file = pd.read_excel("Equations.xlsx")
var1 = file["v1_name"]
vars()[var1] = np.random.rand(10,1)*(3-1)+1
print(var1, sigma)

The output of this is "sigma", which is the name of v1 and then I get the error:

NameError: name 'sigma' is not defined

If, on the other hand I do this:

var1 = "sigma"
vars()[var1] = np.random.rand(10,1)*(3-1)+1
print(var1, sigma)

I get the right output (a list of 10 numbers) with no error.

I printed var1 and the spelling of sigma is correct. I checked if the type is a string (in the first case) and it is. I spent way too much time on this. Can someone please help me? Thank you!

JohnDoe122
  • 638
  • 9
  • 23
  • 2
    No, you have a string you want to use as a `dict` key. Variable names shouldn't have any direct relation with input. – chepner Feb 10 '19 at 17:35
  • Check if `file['v1_name']` doesn't contain any whitespaces, doesn't start with a number... ? – rockikz Feb 10 '19 at 17:38

0 Answers0