Python 如何知道函数的结尾在哪里?

发布于 2024-08-08 02:24:02 字数 290 浏览 1 评论 0原文

我刚刚学习 python,当函数的“def”结束时感到困惑?

我看到这样的代码示例:

def myfunc(a=4,b=6):
    sum = a + b
    return sum

myfunc()

我知道它不会因为返回而结束(因为我见过 if 语句... if FOO 比 return BAR,否则返回 FOOBAR)。 Python 如何知道这不是一个调用自身的递归函数?当函数运行时,它是否会继续执行程序直到找到返回?这会导致一些有趣的错误。

谢谢

I'm just learning python and confused when a "def" of a function ends?

I see code samples like:

def myfunc(a=4,b=6):
    sum = a + b
    return sum

myfunc()

I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

窝囊感情。 2024-08-15 02:24:02

在 Python 中,空格很重要。当缩进变小(更少)时,函数结束。

def f():
    pass # first line
    pass # second line
pass # <-- less indentation, not part of function f.

注意,一行函数可以不缩进地写在一行上:

def f(): pass

并且,然后还有分号的使用,但是不推荐

def f(): pass; pass

上面的三种形式显示了如何结束函数是按语法定义的。至于语义,在 Python 中,退出函数有三种方法:

  • 使用 return 语句。这与您可能知道的任何其他命令式编程语言的工作原理相同。

  • 使用yield语句。这意味着该函数是一个生成器。解释其语义超出了本答案的范围。看看有人能给我解释一下python的yield语句吗?

  • 只需执行最后一条语句即可。如果没有更多语句并且最后一个语句不是 return 语句,则该函数的存在就像最后一个语句是 return None 一样。也就是说,如果没有显式的 return 语句,函数将返回 None。该函数返回None

    <前><代码>def f():
    经过

    这个也是如此:

    <前><代码>def f():
    42

In Python whitespace is significant. The function ends when the indentation becomes smaller (less).

def f():
    pass # first line
    pass # second line
pass # <-- less indentation, not part of function f.

Note that one-line functions can be written without indentation, on one line:

def f(): pass

And, then there is the use of semi-colons, but this is not recommended:

def f(): pass; pass

The three forms above show how the end of a function is defined syntactically. As for the semantics, in Python there are three ways to exit a function:

  • Using the return statement. This works the same as in any other imperative programming language you may know.

  • Using the yield statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at Can somebody explain me the python yield statement?

  • By simply executing the last statement. If there are no more statements and the last statement is not a return statement, then the function exists as if the last statement were return None. That is to say, without an explicit return statement a function returns None. This function returns None:

    def f():
        pass
    

    And so does this one:

    def f():
        42
    
梅倚清风 2024-08-15 02:24:02

Python 在缩进方面对空格敏感。一旦缩进级别回落到定义函数的级别,函数就结束了。

Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended.

仙女山的月亮 2024-08-15 02:24:02

准确地说,当块遇到与开头缩进最多相同级别的非空行时,块就会结束。该非空行不是该块的一部分
例如,以下打印同时结束两个块:

def foo():
    if bar:
        print "bar"

print "baz" # ends the if and foo at the same time

缩进级别小于或等于 def 和 if,因此它结束它们。

没有语句的行,无论缩进如何,都无关紧要,

def foo():
    print "The line below has no indentation"

    print "Still part of foo"

但是标记块结尾的语句必须与任何现有缩进处于同一级别的缩进。那么,以下是一个错误:

def foo():
    print "Still correct"
   print "Error because there is no block at this indentation"

通常,如果您习惯使用花括号语言,只需像它们一样缩进代码就可以了。

顺便说一句,“标准”缩进方式是仅使用空格,但当然仅使用制表符也是可能的,但请不要将两者混合使用。

To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block
For example, the following print ends two blocks at the same time:

def foo():
    if bar:
        print "bar"

print "baz" # ends the if and foo at the same time

The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.

Lines with no statement, no matter the indentation, does not matter

def foo():
    print "The line below has no indentation"

    print "Still part of foo"

But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:

def foo():
    print "Still correct"
   print "Error because there is no block at this indentation"

Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.

BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.

笑着哭最痛 2024-08-15 02:24:02

有趣的是,如果您只是在 python 交互式解释器中输入,则必须在函数后面添加一个空行。这不起作用:

def foo(x):
  return x+1
print "last"

尽管它在文件中是完全合法的 python 语法。在解释器中输入时也存在其他语法差异,所以要小心。

Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:

def foo(x):
  return x+1
print "last"

although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.

黑白记忆 2024-08-15 02:24:02

空白很重要。当块完成时,函数定义也完成。

当函数运行时,它会一直运行直到完成,或者直到遇到 returnyield 语句。如果函数完成时没有遇到 returnyield 语句,则隐式返回 None

教程中有更多信息。

white spaces matter. when block is finished, that's when the function definition is finished.

when function runs, it keeps going until it finishes, or until return or yield statement is encountered. If function finishes without encountering return or yield statements None is returned implicitly.

there is plenty more information in the tutorial.

江城子 2024-08-15 02:24:02

所以缩进很重要。正如这里的其他用户向您指出的那样,当缩进级别与 def 函数声明处于同一点时,您的函数就结束了。请记住,在 Python 中不能混合使用制表符和空格。大多数编辑器都对此提供支持。

So its the indentation that matters. As other users here have pointed out to you, when the indentation level is at the same point as the def function declaration your function has ended. Keep in mind that you cannot mix tabs and spaces in Python. Most editors provide support for this.

失退 2024-08-15 02:24:02

它使用缩进

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

It uses indentation

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 
爱人如己 2024-08-15 02:24:02

我认为,最好通过注释显式地标记函数的结束。

def func():
     # funcbody
     ## end of subroutine func ##

要点是,有些子程序很长,不方便向上滚动编辑器来检查哪个函数结束。另外,如果你使用Sublime,可以右键-> Goto Definition 会自动跳转到子程序声明处。

In my opinion, it's better to explicitly mark the end of the function by comment

def func():
     # funcbody
     ## end of subroutine func ##

The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文