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循环中解除变量的定标,并使其成为整个函数的局部变量?_Python_Variables - Fatal编程技术网

Python 如何从for循环中解除变量的定标,并使其成为整个函数的局部变量?

Python 如何从for循环中解除变量的定标,并使其成为整个函数的局部变量?,python,variables,Python,Variables,我想使一个变量不是脚本的全局变量,而是函数内部的局部变量,但是它是在for循环中生成的,那么我如何从for循环中解除变量的定位,并使函数成为它的父函数呢?例如: def my_function(Array): for i in Array: if ... : Item=i # 'Item' is the variable created in the loop which i want to make local

我想使一个变量不是脚本的全局变量,而是函数内部的局部变量,但是它是在for循环中生成的,那么我如何从for循环中解除变量的定位,并使函数成为它的父函数呢?例如:

def my_function(Array):
    for i in Array:
        if ... :
            Item=i     # 'Item' is the variable created in the loop which i want to make local 
                      # to the function instead of just local to only the for loop.
我已经知道如何调用
null
(或
None
)变量,但我不想这样做,我必须在for循环中创建变量

请注意,这是伪代码


另外,我没有包括if语句的条件,因为它是不必要的,因为这只是一个示例。

在函数内部定义var,它将在运行时被for循环更改,然后返回以将其带到函数外部。

您了解python的作用域规则吗?循环不会创建作用域here@RobinZigmond. 我认为你混淆了Python和JavaScript。Python没有“let”或“var”。@RobinZigmond,我不知道你在说什么。检查语法,因为它似乎是JavaScript。在Python中,所有不在lambda或comprehension中的变量都有函数作用域。在原始程序中,
i
将具有上次在循环结束时接收到的任何值。如果在程序中,您只需在“If”之后“break”,则
i
将具有您想要的值。然而,你可能不得不担心如果数组为空会发生什么。哎呀,对不起——我确实认为这是一个Javascript问题,抱歉,请忽略我(现在已删除)的评论。我需要在for循环中创建变量,我不想预先定义它。你说你不希望它被全局定义。全局变量和函数内部定义的变量之间存在差异。