Python def 函数:如何指定函数的结尾? [英] Python def function: How do you specify the end of the function?

查看:57
本文介绍了Python def 函数:如何指定函数的结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 python 并且在函数的def"结束时感到困惑?

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()

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

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.

谢谢

推荐答案

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

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

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

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:

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

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

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

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?

通过简单地执行最后一条语句.如果没有更多语句并且最后一个语句不是 return 语句,那么该函数就如同最后一个语句是 return None 一样存在.也就是说,如果没有明确的return 语句,函数将返回None.此函数返回None:

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

这个也是:

def f():
    42

这篇关于Python def 函数:如何指定函数的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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