Python使用函数作为参数的变量范围

时间:2013-05-01 21:39:07

标签: python scope

def fvals_sqrt(x):
   """
   Return f(x) and f'(x) for applying Newton to find a square root.
   """
   f = x**2 - 4.
   fp = 2.*x
   return f, fp

def solve(fvals_sqrt, x0, debug_solve=True):
   """
   Solves the sqrt function, using newtons methon.
   """
   fvals_sqrt(x0)
   x0 = x0 + (f/fp)
   print x0

当我尝试调用函数solve时,python返回:

NameError: global name 'f' is not defined

显然这是一个范围问题,但我如何在我的求解函数中使用f?

4 个答案:

答案 0 :(得分:3)

您正在调用fvals_sqrt()但不对返回值执行任何操作,因此会将其丢弃。返回变量不会神奇地使它们存在于调用函数中。你的电话应该是这样的:

f, fp = fvals_sqrt(x0)

当然,您不需要使用与您正在调用的函数的return语句中使用的变量相同的名称。

答案 1 :(得分:3)

问题是你没有在函数调用中存储返回的值:

f,fp = fvals_sqrt(x0)

答案 2 :(得分:3)

你想要这个:

def solve(fvals_sqrt, x0, debug_solve=True):
    """
    Solves the sqrt function, using newtons methon.
    """
    f, fp = fvals_sqrt(x0) # Get the return values from fvals_sqrt
    x0 = x0 + (f/fp)
    print x0

答案 3 :(得分:1)

您需要使用此行

展开fvals_sqrt(x0)的结果
f, fp = fvals_sqrt(x0)

在全球范围内,您应该尝试

def fvals_sqrt(x):
   """
   Return f(x) and f'(x) for applying Newton to find a square root.
   """
   f = x**2 - 4.
   fp = 2.*x
   return f, fp

def solve(x0, debug_solve=True):
   """
   Solves the sqrt function, using newtons methon.
   """
   f, fp = fvals_sqrt(x0)
   x0 = x0 + (f/fp)
   print x0

solve(3)

结果

>>> 
3.83333333333