Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从嵌套在for循环中的if语句生成全局变量_Python_Variables_Scope_Global Variables - Fatal编程技术网

Python 从嵌套在for循环中的if语句生成全局变量

Python 从嵌套在for循环中的if语句生成全局变量,python,variables,scope,global-variables,Python,Variables,Scope,Global Variables,我有一个典型的新手问题,就是如何将函数的结果放入全局范围,我通常可以在简单的示例中了解局部和全局变量的工作方式,但我很难理解当for循环中嵌套if语句时会发生什么 下面是我正在使用的原始代码。我正在尝试将此项目的结果扩展到全局范围 def getTheFirstPoint(selection): for thisItem in selection: if type(thisItem) == GSNode: print 'LOCAL', thisIt

我有一个典型的新手问题,就是如何将函数的结果放入全局范围,我通常可以在简单的示例中了解局部和全局变量的工作方式,但我很难理解当for循环中嵌套if语句时会发生什么

下面是我正在使用的原始代码。我正在尝试将此项目的结果扩展到全局范围

def getTheFirstPoint(selection):
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'LOCAL', thisItem
            return thisItem
    return None
我一直在尝试这样的事情:

thisItem = ''

def getTheFirstPoint(selection):
    global thisItem
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'LOCAL', thisItem
            #return thisItem
    #return None

getTheFirstPoint(thisItem)
print 'GLOBAL:', thisItem
我有时看到全局变量不需要在函数外部显式设置——我需要“thisItem=”

有必要申报吗

我需要做什么才能全局访问此项目

任何帮助都将不胜感激。

如果您运行以下代码:

thiItem = ''
在函数定义中,将创建新的局部变量。如果您确实在函数中运行下面的代码

global thisItem
thisItem = ''
全局变量将被修改。当运行
for
循环时,在[iterable]中为[newVarName]创建新的局部变量
。将此项定义为全局后,不要在for循环中再次使用此名称

如果您希望在条件下修改全局变量,则以下代码将执行此操作:

thisItem = ''

def getTheFirstPoint(selection):
    global thisItem
    for item in selection:
        if type(item) == GSNode:
            print 'LOCAL', item
            # Modify global variable.
            thisItem = item
            #return thisItem
    #return None

getTheFirstPoint(thisItem)
print 'GLOBAL:', thisItem

<强> P.S.我有一种感觉,可能对你来说是充分利用的,也考虑更密切地了解关于.< /P> < P> <强>的信息。有时我看到,全局变量不需要在函数外显式设置。我需要“TestIt==”吗?< /强> 如果在函数中创建变量thisItem,则会在该函数中创建局部变量。如果你使用

previous_function():
    thisItem = ''
new_function():
    global thisItem 
    thisItem = 'updated value'
然后,在new_函数中调用该值时,该值将被覆盖。这就是为什么需要在任何其他函数之外定义它

是否需要退货? 不,不需要退货。正如您可以从任何其他函数调用全局变量一样。如果有另一个同名变量,则需要指定要使用全局定义,而不是上面示例中的本地定义

我需要做什么才能全局访问此项目? 您可以按如下方式使用它:

thisItem = ''
def getTheFirstPoint(selection):
    for thisItem in selection:
        if type(thisItem) == GSNode:
            print 'GLOBAL', thisItem
def some_new_function():
    global thisItem
    thisItem = 'modified value'