Python: 在另一个函数中使用局部变量

Python: use a local variable in another function

我想知道如何访问 for 循环中的局部变量并在另一个函数中使用该变量。这是我的问题的一个非常简单的例子:

def function():
  i = 0
  z = 2
    for i in range(0,5):
      x = i + z
      print "x value is:",
      print x,
      print "and i value is:",
      print i

这是函数的输出:

x value is: 2 and i value is: 0
x value is: 3 and i value is: 1
x value is: 4 and i value is: 2
x value is: 5 and i value is: 3
x value is: 6 and i value is: 4

最重要的是我不能修改变量i或变量z我用python 2.7

如果我简化我的问题,我想要类似的东西,但做得很好:

def function():
  i = 0
  z = 2

  for i in range(0,5):
    x = i + z

if (i==3):
    print x #x value when i = 3
else:
    #something

我试图通过调用它来使变量 x 可访问 functionA.x 但是 returns x 拥有的最后一个值,我有兴趣根据变量 i 了解它的值。

我怎样才能简单地做到这一点? 谢谢。

为什么不这样做:

def function():
  i = 0
  z = 2

  for i in range(0,5):
    x = i + z
    if (i==3):
      print x #x value when i = 3
    else:
      #something

函数() 在任何情况下,仅当首先调用该函数时,您才可以在其他地方访问函数变量:

def function():
    i = 0 # this is redundant, python generates a list with range and the variable 'i' below takes on each value in that list.
    z = 2
#    something
#    something
    for i in range(0,5):
        function.x = i + z
        function.i = i
function()
print function.i
##Below will never execute and print because the value of i is 4 always because the for loop as interated to its last value
if (function.i==3):
    print function.x
else:
    #something

另一种选择是在您的函数中使用 return