python中exec中变量不能保存,函数内部使用exec(astring)和astring中的变量定义无法在python 3中返回变量...

本文探讨了在Python中如何通过`exec`和`eval`函数将字符串转换为可执行的代码。示例中,尝试将字符串'np.pi'定义为变量并返回其值,但遇到了`NameError`。解决方案包括使用`eval`来正确地执行包含函数调用的字符串表达式。
摘要由CSDN通过智能技术生成

I have a python 3 function that takes a string of commands, say 'np.pi' and then tries to define a variable with that string. Then I try to return the variable, this however does not work.

input = np.pi

astring = 'funcD(funcC(funcB(funcA(input))))'

def function(astring):

astring= 'variable = ' + astring

exec(astring)

return variable

In: a = function(astring)

Out: NameError: global name 'variable' is not defined

Nothing seems to have happened. What I would like is to have the function return the output of the command in the string. The string contains several functions who have each other as input like below. I tried putting the exec after return without adding the variable = and then call the function with a = function(astring) but that did not work either. I believe I cant use eval because my string has functions in it.

解决方案

You didn't state what you expected from the answer, so I take a guess: You want to make this work.

Try it using eval:

def function(astring):

astring= 'variable = ' + astring

exec(astring)

return eval('variable')

function('42')

returns as expected 42.

Or simply strip that assignment:

def function(astring):

return eval(astring)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值