8.2. Function Return

8.2.1. Syntax

def my_function():
    return <expression>
def add_numbers(a, b):
    return a + b
def mean(a, b):
    c = (a+b) / 2
    return c

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(first_name='Mark', last_name='Watney')

def my_function():
    return {'first_name': 'Mark', 'last_name': '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': (set(), tuple(), list())},
    ]

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. Assignments

8.2.8.1. Return Numbers

English
  1. Define function add without parameters

  2. Function should return sum of 42 and 13.37

  3. Call function and intercept returned value

  4. Print value

Polish
  1. Zdefiniuj funkcję add bez parametrów

  2. Funkcja powinna zwracać sumę 42 and 13.37

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

  4. Wyświetl wartość