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 。
python 返回语句