9.1. Function Definition

9.1.1. Function definition

  • Reuse code

  • Improves code readability

  • Clean-up code

  • Allows for easier refactoring

def hello():
    print('My name... José Jiménez')

hello()     # My name... José Jiménez
hello()     # My name... José Jiménez
hello()     # My name... José Jiménez

9.1.2. Naming convention

  • Do not use camelCase names

  • CamelCase is reserved for class names

  • Use snake_case names # Python - snake ;)

  • Add underscore (_) at the end of name when name collide

  • System functions names starts and ends with 'dunder' - double underscore: __

Listing 175. Do not use camelCase, CamelCase is reserved for class names. Use snake_case
def addNumbers(a, b):
    return a + b

def add_numbers(a, b):
    return a + b
Listing 176. Use better names, rather than comments
def cal_var(results, m):
    """Calculate variance"""
    return sum((Xi-m) ** 2 for Xi in results) / len(results)

def calculate_variance(results, m):
    return sum((Xi-m) ** 2 for Xi in results) / len(results)
Listing 177. Add underscore (_) at the end of name when name collide
def print_(text):
    print(f'<strong>{text}</strong>')
Listing 178. System functions names starts and ends with 'dunder' - double underscore: __
def __import__(module_name):
    ...

9.1.3. Docstring

  • Docstring is a first multiline comment in:

    • File / Module

    • Class

    • Method / Function

  • It is accessible in __doc__ property of an object

  • Used for generating help() documentation

  • Used for doctest (more in Function Doctest)

  • PEP 257 Docstring convention - For multiline always use three double quote (""") characters

Listing 179. Docstring used for documentation
def my_function():
    """
    This is the My Function
    """
    print('Hello')


help(my_function)
# Help on function my_function in module __main__:
#
# my_function()
#     This is the My Function

print(my_function.__doc__)
# This is the My Function

9.1.4. Assignments

9.1.4.1. Define Function

  • Complexity level: easy

  • Lines of code to write: 5 lines

  • Estimated time of completion: 5 min

  • Solution: solution/define_print.py

English
  1. Define function call without parameters

  2. Print Beetlejuice on the screen

  3. Call function three times

Polish
  1. Zdefiniuj funkcję call bez parametrów

  2. Wypisz Beetlejuice na ekranie

  3. Wywołaj funkcję trzy razy