8.2. Function Return

8.2.1. Syntax

def my_function():
    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 function

  • Code after return will not execute

def hello():
    return 'ehlo world'

print(hello())
# 'ehlo world'
def hello():
    return 'ehlo world'
    print('This will not be executed')

print(hello())
# 'ehlo world'

8.2.3. Return Basic Type

def my_function():
    return 42
def my_function():
    return 13.37
def my_function():
    return 'Mark Watney'
def my_function():
    return True

8.2.4. Return Sequence

def my_function():
    return list([42, 13.37, 'Mark Watney'])

def my_function():
    return [42, 13.37, 'Mark Watney']
def my_function():
    return tuple((42, 13.37, 'Mark Watney'))

def my_function():
    return (42, 13.37, 'Mark Watney')

def my_function():
    return 42, 13.37, 'Mark Watney'
def my_function():
    return set({42, 13.37, 'Mark Watney'})

def my_function():
    return {42, 13.37, 'Mark Watney'}
def my_function():
    return frozenset({42, 13.37, 'Mark Watney'})

8.2.5. Return Mapping

def my_function():
    return dict(firstname='Mark', lastname='Watney')

def my_function():
    return {'firstname': 'Mark', 'lastname': 'Watney'}

8.2.6. Return Nested Sequence

def my_function():
    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 my_function():
    return None
def my_function():
    print('ehlo world')
def my_function():
    pass
def my_function():
    """My function"""

8.2.8. Intercept returned value

def my_function():
    return 1


result = my_function()
print(result)
# 1

8.2.9. Assignments

8.2.9.1. Function Return Numbers

  • Assignment name: Function Return Numbers

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 4 lines

  • Estimated time of completion: 3 min

  • Solution: solution/function_return_numbers.py

English
  1. Define function add without parameters

  2. Function should return sum of 1 and 2

  3. Call function and intercept returned value

  4. Print value

Polish
  1. Zdefiniuj funkcję add bez parametrów

  2. Funkcja powinna zwracać sumę 1 i 2

  3. Wywołaj funkcję i przechwyć zwracaną wartość

  4. Wyświetl wartość