8.2. Function Return¶
8.2.1. Syntax¶
def myfunction():
return <expression>
>>> def mean():
... return (1+2) / 2
>>> def add():
... a = 1
... b = 2
... return a + b
8.2.2. Return Keyword¶
return
keyword indicates outcome of the functionCode after
return
will not execute
>>> def hello():
... return 'hello world'
>>>
>>>
>>> hello()
'hello world'
>>> def hello():
... return 'hello world'
... print('This will not be executed')
>>>
>>>
>>> hello()
'hello world'
8.2.3. Return Basic Type¶
>>> def myfunction():
... return 42
>>> def myfunction():
... return 13.37
>>> def myfunction():
... return 'Mark Watney'
>>> def myfunction():
... return True
8.2.4. Return Sequence¶
>>> def myfunction():
... return list([42, 13.37, 'Mark Watney'])
>>> def myfunction():
... return [42, 13.37, 'Mark Watney']
>>> def myfunction():
... return tuple((42, 13.37, 'Mark Watney'))
>>> def myfunction():
... return (42, 13.37, 'Mark Watney')
>>> def myfunction():
... return 42, 13.37, 'Mark Watney'
>>> def myfunction():
... return set({42, 13.37, 'Mark Watney'})
>>> def myfunction():
... return {42, 13.37, 'Mark Watney'}
>>> def myfunction():
... return frozenset({42, 13.37, 'Mark Watney'})
8.2.5. Return Mapping¶
>>> def myfunction():
... return dict(firstname='Mark', lastname='Watney')
>>> def myfunction():
... return {'firstname': 'Mark', 'lastname': 'Watney'}
8.2.6. Return Nested Sequence¶
>>> def myfunction():
... return [
... ('Mark', 'Watney'),
... {'Jan Twardowski', 'Melissa Lewis'},
... {'astro': 'Иванович', 'agency': {'name': 'Roscosmos'}},
... {'astro': 'Jiménez', 'missions': ('Mercury', 'Gemini', 'Apollo')},
... {'astro': 'Vogel', 'missions': (list(), tuple(), set(), frozenset())},
... ]
8.2.7. Return None¶
Python will
return None
if no explicit return is specified
>>> def myfunction():
... return None
>>> def myfunction():
... print('hello')
>>> def myfunction():
... pass
>>> def myfunction():
... """My function"""
8.2.8. Intercept returned value¶
>>> def myfunction():
... return 1
>>>
>>>
>>> result = myfunction()
>>> print(result)
1
8.2.9. Assignments¶
"""
* Assignment: Function Return Numbers
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Define function `compute` without parameters
2. Function should return sum of `1` and `2`
3. Define `result` with result of function call
Polish:
1. Zdefiniuj funkcję `compute` bez parametrów
2. Funkcja powinna zwracać sumę `1` i `2`
3. Zdefiniuj `resul` z wynikiem wywołania funkcji
Tests:
>>> from inspect import isfunction
>>> isfunction(compute)
True
>>> result
3
"""