python 返回语句_Python返回语句解释:它们是什么以及为什么使用它们

python 返回语句

All functions return a value when called.

所有函数在调用时都返回一个值。

If a return statement is followed by an expression list, that expression list is evaluated and the value is returned:

如果在return语句后跟随一个表达式列表,则将对该表达式列表求值并返回值:

>>> def greater_than_1(n):
...     return n > 1
...
>>> print(greater_than_1(1))
False
>>> print(greater_than_1(2))
True

If no expression list is specified, None is returned:

如果未指定表达式列表,则返回None

>>> def no_expression_list():
...     return    # No return expression list.
...
>>> print(no_expression_list())
None

If a return statement is reached during the execution of a function, the current function call is left at that point:

如果在函数执行过程中到达return语句,则当前函数调用将留在该点:

>>> def return_middle():
...     a = 1
...     return a
...     a = 2     # This assignment is never reached.
...
>>> print(return_middle())
1

If there is no return statement the function returns None when it reaches the end:

如果没有return语句,则函数到达末尾时将返回None:

>>> def no_return():
...     pass     # No return statement.
...
>>> print(no_return())
None

A single function can have multiple return statements. Execution of the function ends when one of these return statements is reached:

一个函数可以有多个return语句。 当到达以下return语句之一时,函数的执行结束:

>>> def multiple_returns(n):
 ...    if(n):
 ...        return "First Return Statement"
 ...    else:
 ...        return "Second Return Statement"
 ...
 >>> print(multiple_returns(True))
 First Return Statement
 >>> print(multiple_returns(False))
 Second Return Statement

A single function can return various types:

一个函数可以返回各种类型:

>>> def various_return_types(n):
 ...     if(n==1):
 ...         return "Hello World."   # Return a string
 ...     elif(n==2):
 ...         return 42               # Return a value
 ...     else:
 ...         return True             # Return a boolean
 ... 
 >>> print(various_return_types(1))
 Hello World.
 >>> print(various_return_types(2))
 42
 >>> print(various_return_types(3))
 True

It is even possible to have a single function return multiple values with only a single return:

甚至可能有一个函数仅返回一个就返回多个值:

>>> def return_two_values():
 ...     a = 40
 ...     b = 2
 ...     return a,b
 ...
 >>> print("First value = %d,  Second value = %d" %(return_two_values()))
 First value = 40,  Second value = 2

See the Python Docs for more info.

有关更多信息,请参见Python Docs

翻译自: https://www.freecodecamp.org/news/python-return-statements-explained-what-they-are-and-why-you-use-them/

python 返回语句

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值