python函数中变量的作用域?

2024-10-01 07:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新的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''')

Tags: theinforstringvaluedefevalsome
1条回答
网友
1楼 · 发布于 2024-10-01 07:16:51

some_func中,i是一个局部变量。局部变量不能在函数外访问。你知道吗

在第二种情况下,i是一个全局变量,因此函数可以访问全局变量。你知道吗

如果您想这样做,只需将i传递给some_func

def try_print(string, i):
    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''', i)

但使用eval并不是一个好主意,只需使用字符串格式:

print "Trying to print the value of %s" %i

相关问题 更多 >