Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.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变量范围_Python_Scope - Fatal编程技术网

以函数作为参数的Python变量范围

以函数作为参数的Python变量范围,python,scope,Python,Scope,当我尝试调用函数solve时,python返回: 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 functi

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

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函数中使用f呢?

您正在调用
fvals\u sqrt()
,但不处理返回值,因此它们被丢弃。返回变量不会神奇地使它们存在于调用函数中。你的电话应该是这样的:

NameError: global name 'f' is not defined

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

问题在于,您没有将函数调用返回的值存储在任何位置:

f, fp = fvals_sqrt(x0)
你想要这个:

f,fp = fvals_sqrt(x0)

您需要使用此行展开
fvals_sqrt(x0)
的结果

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
在全球范围内,你应该试试

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