Python-如何在函数中返回工作 [英] Python- How does return work in function

查看:120
本文介绍了Python-如何在函数中返回工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我有这样的代码

  def calculate(a):
a = int(a)
返回一个#或产生一个

然后我写成:

  def _convert(a):
a = int (a)
返回一个#或产生a + 1

def calculate(a):
_convert(a)#这是正确的还是我需要的(return _convert(a) )

-
内部返回函数是否​​一直到最后?

解决方案

return 语句允许您确定函数调用需要一个表达式。如果一个函数调用另一个函数,则第二个函数将返回一个值到第一个函数。



因此,在第二个示例中,为了 calculate 返回一个值给它的调用者,它必须使用 return 语句,所以 return _convert(a)

通过在交互式解释器中运行这些答案可以很容易地确定这些答案,我经常鼓励初学者为此目的使用它们。 / p>

I am confused with using functions in python.

Suppose i have this code

def calculate(a):
    a = int(a)
    return a  # or yield a

Then i write as

def _convert(a):
    a = int(a)
    return a # or yield a+1

def calculate(a):
    _convert(a)  # is this correct or i need (return _convert(a))

-- Does the internal return function goes till the end?

解决方案

The return statement allows you to determine the value that a function call takes in an expression. If one function calls another, the the second functions returns a value to the first.

Thus in your second example, in order for calculate to return a value to its caller it must indeed use a return statement, and so return _convert(a) would indeed be correct.

Such answers can easily be determined by running them in the interactive interpreter, which I often encourage beginners to use for just that purpose.

这篇关于Python-如何在函数中返回工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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