[Solved] turning a string into a variable (bad operand type for unary +: ‘str’) [closed]


You didn’t provide enough information, but my psychic powers tell me that when you were prompted with “Enter an animal “, you typed input.

Try to mentally walk through what your code is doing, particularly when you get to:

exec("%s = %s" % (i[3::], raw_input("Enter " + i + " ")))

So for the first iteration through the loop, this becomes:

exec("%s = %s" % ("animal", "input"))

Then when the substitution happens:

exec("animal = input")

Which is equivalent to typing:

animal = input

directly into the Python interpreter. input isn’t defined, so you get:

NameError: name 'input' is not defined

You probably meant to surround the right-hand side with quotes to treat it as a string when executed:

 exec("%s="%s"" % ("animal", "input")) # Note that this is unsafe.  See the note below.

All that being said, I feel obligated to say that this code is incredibly brittle. When the loop iterates to “A superhero name”, it will also break because superhero name isn’t a valid identifier. You instead probably should split the string on spaces and perhaps take the second word, or just replace all spaces with, say, underscores. Additionally, you will need to sanitize user input so that a user can’t escape by supplying quotes in the input. (Or even better would be to avoid using exec with user input entirely. Do you really need variable names? Why not just use a Python dictionary mapping the prompted strings to the input strings?)

solved turning a string into a variable (bad operand type for unary +: ‘str’) [closed]