每个 Python 函数最后都必须返回吗? [英] Does every Python function have to return at the end?

查看:35
本文介绍了每个 Python 函数最后都必须返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在制作一个递归函数的图表来环绕递归,我注意到显然每个函数最后都执行 return?

另一个问题,函数到底返回什么?传递给它的所有参数(假设有多个参数)?或者某种价值?

(t 只是一个执行实际绘制的实体)

def koch(t, n):"""绘制一条长度为n的科赫曲线."""如果n<30:fd(t, n)返回m = n/3.0科赫(t, m)lt(t, 60)科赫(t, m)rt(t, 120)科赫(t, m)lt(t, 60)科赫(t, m)

解决方案

所以我正在制作一个递归函数的图表来环绕递归,我注意到显然每个函数最后都执行 return?

return 本身仅仅意味着调用帧调用栈程序计数器中弹出设置回您拨打电话之前的状态,等等.根据您的评论,它看起来回溯",但请注意 - 与回溯相反- 函数具有的副作用,不会恢复/撤消.例如,追加到列表、画线、写入文件等都不会恢复.这是递归中所需的行为.

现在有时返回某个值很有用.例如:

def foo(x,y):返回 x+y

这里 foo 不仅返回给调用者,而且首先计算 x+y 并返回结果,这样你就可以声明 z =foo(2,3).所以这里foo被调用,2+3被求值,5被返回并分配给z.><块引用>

另一个问题,函数到底返回什么?传递给它的所有参数(假设有多个参数)?

在 Python 中所有函数都返回一个值.如果你指定它像:

return <表达式>

部分被评估并返回该值.如果您指定:

返回

或者根本没有return(但是你到达了函数的末尾),None 将被返回.

So I was making a diagram of the recursive function to wrap my head around recursion, and I noticed that apparently every function executes return at the end?

Another question, what exactly does a function return? All parameters passed to it (assuming multiple parameters)? Or some kind of value?

(t is just an entity that performs actual drawing)

def koch(t, n):
    """Draws a koch curve with length n."""
    if n<30:
        fd(t, n)
        return
    m = n/3.0
    koch(t, m)
    lt(t, 60)
    koch(t, m)
    rt(t, 120)
    koch(t, m)
    lt(t, 60)
    koch(t, m)

解决方案

So I was making a diagram of the recursive function to wrap my head around recursion, and I noticed that apparently every function executes return at the end?

A return itself simply means that the call frame is popped from the call stack, the program counter is set back to state where it was before you made the call, etc. Based on your comment it looks a bit like "backtracking" but mind that - in contrast to backtracking - side effects the functions have, are not reverted/undone. For instance appending to a list, drawing a line, writing to a file, etc. are not reverted. This is the desired behavior in recursion.

Now sometimes it is useful to return a certain value. For instance:

def foo(x,y):
    return x+y

here foo does not only go back to the caller, but first evaluates x+y and the result is returned, such that you can state z = foo(2,3). So here foo is called, 2+3 is evaluated and 5 is returned and assigned to z.

Another question, what exactly does a function return? All of parameters passed to it (assuming multiple parameters)?

In Python all functions return a value. If you specify it like:

return <expression>

the <expression> part is evaluated and that value is returned. If you specify:

return

or no return at all (but you reach the end of the function), None will be returned.

这篇关于每个 Python 函数最后都必须返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆