简体   繁体   English

Python def 函数:如何指定函数的结尾?

[英]Python def function: How do you specify the end of the function?

I'm just learning python and confused when a "def" of a function ends?我只是在学习 python 并且在函数的“def”结束时感到困惑?

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).我知道它不会因为返回而结束(因为我已经看到 if 语句......如果 FOO 比返回 BAR,否则返回 FOOBAR)。 How does Python know this isn't a recursive function that calls itself? Python 怎么知道这不是一个调用自身的递归函数? 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谢谢

In Python whitespace is significant.在 Python 中,空格很重要。 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:至于语义,在 Python 中有三种退出函数的方式:

  • Using the return statement.使用return语句。 This works the same as in any other imperative programming language you may know.这与您可能知道的任何其他命令式编程语言的工作方式相同。

  • Using the yield statement.使用yield语句。 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?看看有人可以向我解释 python yield 语句吗?

  • 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 .如果没有更多语句并且最后一个语句不是return语句,则该函数存在,就好像最后一个语句是return None That is to say, without an explicit return statement a function returns None .也就是说,如果没有明确的return语句,函数将返回None This function returns None :此函数返回None

     def f(): pass

    And so does this one:这个也是如此:

     def f(): 42

Python is white-space sensitive in regard to the indentation. Python 在缩进方面对空格敏感。 Once the indentation level falls back to the level at which the function is defined, the function has ended.一旦缩进级别回落到定义函数的级别,函数就结束了。

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.缩进级别小于或等于 def 和 if,因此它结束它们。

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.顺便说一句,缩进的“标准”方式是仅使用空格,但当然只能使用制表符,但请不要将两者混合使用。

Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line.有趣的是,如果您只是在 python 交互式解释器中键入,则必须在函数后面加上一个空行。 This does not work:这不起作用:

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

although it is perfectly legal python syntax in a file.尽管它在文件中是完全合法的 python 语法。 There are other syntactic differences when typing to the interpreter too, so beware.在向解释器输入时也有其他语法差异,所以要小心。

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.当函数运行时,它会一直运行直到完成,或者直到遇到returnyield语句。 If function finishes without encountering return or yield statements None is returned implicitly.如果函数在没有遇到returnyield语句的情况下完成,则隐式返回None

there is plenty more information in the tutorial . 教程中有更多信息。

It uses indentation它使用缩进

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

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.正如这里的其他用户向您指出的那样,当缩进级别与 def 函数声明处于同一点时,您的函数就结束了。 Keep in mind that you cannot mix tabs and spaces in Python.请记住,您不能在 Python 中混合使用制表符和空格。 Most editors provide support for this.大多数编辑器对此提供支持。

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.另外,如果你使用Sublime,你可以右键-> Goto Definition,它会自动跳转到子程序声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM