我是新的python&在我的代码中尝试使用eval表达式,如下所示, 当我调用some_func()(注释)时,我得到“NameError:name'i'未定义” 但是当我直接调用try\u print funct时,如下所示可以打印i的值
直接调用try\u print和via函数有什么区别?你知道吗
如何使用some_func()实现这一点?你知道吗
def try_print(string):
print eval(string)
def some_func():
global gameset
gameset = "gamese,gamese1"
for i in gameset.split(","):
try_print('''"Trying to print the value of %s" %i''')
#some_func()
gameset1 = "gamese,gamese1"
for i in gameset1.split(","):
try_print('''"here the value is printed %s" %i''')
在
some_func
中,i
是一个局部变量。局部变量不能在函数外访问。你知道吗在第二种情况下,
i
是一个全局变量,因此函数可以访问全局变量。你知道吗如果您想这样做,只需将
i
传递给some_func
:但使用
eval
并不是一个好主意,只需使用字符串格式:相关问题 更多 >
编程相关推荐