eval(): can't assign to function call

点点圈 提交于 2021-02-05 08:37:09

问题


Yet another question for my cookie clicker... Here is the code I made that produces an error:

cps=cps+bcps[buych]
c=c-bprice[buych]
eval(buych)=eval(buych)+1

cps is a variable,
c is a variable,
b1,b2,b3,b4,b5 are variables
buych is a string (Which I get from an input() command)
bcps and bprice are maps (shown below)

bcps = {"b1":'1',
    "b2":'5',
    "b3":'10',
    "b4":'20',
    "b5":'25'}
bprice = {"b1":'10',
    "b2":'20',
    "b3":'30',
    "b4":'40',
    "b5":'50'}

So, what I'm trying to achieve is:
-Take the input string value, which will be 'b1','b2', 'b3', 'b4', 'b5'
-Increase cps buy it's value within bcps
-Decrease c by it's value within bprice
-Use eval to convert the 'b#' to b#
-Increase b# by 1

When running the script, I do not get error text in the python shell. Instead, I get a pop-up that says "Can't assign to function call". The error is highlighted as the first white space before the eval(). I really don't get this, as I have no functions within the error.

Thanks for reading,
Cookie Monster


回答1:


eval(buych) is a function call -- you're calling the function eval(). You can only assign to variables, you can't assign to the result of a function.

You need to concatenate the variable into a valid assignment expression, and exec that:

exec(buych + '=' + buych + '+1')

eval is for evaluating expressions, you have to use exec to execute a whole statement.

But if you find yourself needing to do this, you're usually doing something wrong. Instead of computing variable names and expressions, you should use lists or dicts so you can refer to them using an index or key.



来源:https://stackoverflow.com/questions/23837006/eval-cant-assign-to-function-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!