Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.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_Function - Fatal编程技术网

Python 定义函数——为什么这个代码是错误的?

Python 定义函数——为什么这个代码是错误的?,python,function,Python,Function,这个代码是错误的;正确的版本发布在下面,但我不明白为什么这不起作用。它似乎结构合理 def absolute_value(x): #define a function "absolute_value" """returns the absolute value of x. """ if x < 0: return x = -x else: return x def absolute_value(x):#定义函数“absolu

这个代码是错误的;正确的版本发布在下面,但我不明白为什么这不起作用。它似乎结构合理

def absolute_value(x): #define a function "absolute_value"
    """returns the absolute value of x.
    """
    if x < 0:
        return x = -x
    else:
        return x
def absolute_value(x):#定义函数“absolute_value”
“”“返回x的绝对值。
"""
如果x<0:
返回x=-x
其他:
返回x
这是正确的代码:

def absolute_value(x): #define a function "absolute_value"
    """returns the absolute value of x.
    """
    if x < 0:
        x = -x
    return x
def absolute_value(x):#定义函数“absolute_value”
“”“返回x的绝对值。
"""
如果x<0:
x=-x
返回x

以下是您第一次尝试的代码:

def absolute_value(x): #define a function "absolute_value"
    """returns the absolute value of x.
    """
    if x < 0:
        return -x
    else:
        return x
如您所见,
x
仍然具有调用之前的值。该值作为返回值传递回调用函数。这就是您需要调用函数来改变x的方式:

>>> print x ; x=absolute_value(x)
-3
>>> print x
3

也就是说,您需要显式地将返回值赋给python中的
x

“return”不能接受语句

我希望这会有所帮助。

不能在同一语句中返回和赋值。因为赋值是一个语句,所以只能返回值。
>>> x = -3
>>> print absolute_value(x)
3
>>> print x
-3
>>> print x ; x=absolute_value(x)
-3
>>> print x
3