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 171. 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 172. 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 173. Add underscore (_) at the end of name when name collide
def print_(text):
    print(f'<strong>{text}</strong>')
Listing 174. 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 175. Docstring used for documentation
def apollo_dsky(noun, verb):
    """
    This is the Apollo Display Keyboard
    It takes noun and verb
    """
    print(f'Program selected. Noun: {noun}, verb: {verb}')

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

  • Filename: solution/define_print.py

English
  1. Define function call

  2. Print Beetlejuice on the screen

  3. Call function three times

Polish
  1. Zdefiniuj funkcję call

  2. Wypisz Beetlejuice na ekranie

  3. Wywołaj funkcję trzy razy