Reputation: 121
I'm trying to use this code to create a while loop from a string, but it's not working. This is the string that I call with the eval() function:
'while True:\n\vprint("What role do you want?")\n\vAnswer = Reformat(raw_input())\n\vif Answer in RoleArray:\n\v\vPlayArray[0].append(Answer)\n\vif Answer == "Mafia":\n\v\v\vMafia.append(User)\n\v\velif Answer == "Sheriff":\n\v\v\vSheriff = User\n\v\velif Answer == "Doctor":\n\v\v\vDoctor = User\n\v\vdel RoleArray[RoleArray.index(Answer)]\n\velse:\n\v\vprint("That is not a role. Please check you spelling. [Mafia/Sheriff/Doctor/Townsperson]")'
And this is the error that shows up:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
eval('while True:\n\vprint("What role do you want?")\n\vAnswer = Reformat(raw_input())\n\vif Answer in RoleArray:\n\v\vPlayArray[0].append(Answer)\n\vif Answer == "Mafia":\n\v\v\vMafia.append(User)\n\v\velif Answer == "Sheriff":\n\v\v\vSheriff = User\n\v\velif Answer == "Doctor":\n\v\v\vDoctor = User\n\v\vdel RoleArray[RoleArray.index(Answer)]\n\velse:\n\v\vprint("That is not a role. Please check you s')
File "<string>", line 1
while True:
^
SyntaxError: invalid syntax
There is an alternate way to execute this code properly, but I would like to know why it isn't working. Thanks.
Upvotes: 0
Views: 1272
Reputation: 9633
The most likely culprit is both your use of \v
instead of \t
for tabs and your use of eval
. You need to fix both:
Fixing both removes the syntax error:
>>> exec("while True:\n\tprint('yup')\n\tbreak")
yup
Using the vertical tab \v
causes a syntax error:
>>> exec("while True:\n\vprint('yup')\n\vbreak")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2
♂print('yup')
^
SyntaxError: invalid syntax
And so does using eval
, which is intended only for expressions:
>>> eval("while True:\n\tprint('yup')\n\tbreak")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
while True:
^
SyntaxError: invalid syntax
See this answer for an explanation of the differences between eval
and exec
.
It's possible you have other syntax errors as well, but I'm not going to try to debug that very long line.
Additionally, you should strongly reconsider your use of the dynamic code consuming functions like eval
and exec
. Even if your code's intended use doesn't present any security risk, they make things much more difficult to debug and maintain. The cases where they can't be avoided are exceedingly rare.
Upvotes: 2
Reputation: 121
After veiwing comments, I realize that I was being really dumb as to not use exec()
instead of eval()
, since one gives me a variable, and the other gives me a variable. Thank you, Blorgbeard!
Upvotes: 0