Pacific Beach Drive

Mike's Drive.

Follow me on GitHub

Functions

Python Style guide

The 3 steps of a function

  1. input
  2. transform
  3. Output

you can do two things with functions

  • Define it (a block of re-usable code => loop)
  • call it
# define the function
def do_nothing(parameters):
        # since functions do something, use a verb as function name
    pass

# call the function
do_nothing()

Examples of functions

  • len
  • open
  • reversed
  • password_validator

Programming interface

  • Function caller (client) only needs to know about the inputs and output
    • Implementation details are hidden, how it does the processing is hidden from us (Like a black box)
  • Because we don’t know the implementation we can concentrate on higher level thingking - how modules work together, instead of how they work.

Calling Functions

  • function name and parenthesis and values (arguments within the parenthesis)
  • number of arguments depends on the function’s defintion

Function implementation

  • is ideally self contained.
  • we will only change this part of code should we need to fix bugs or come up with a better algorithm
  • we use parameters as part of the processing
  • Returns an output

Readability counts docstring vs comments [Zen of Python]

docstring describes the function’s external behavior, and the parameters it takes. comments should document internal info about how the code works.

  • documentation to a function definition (page 152)
def echo(anything):
    'echo returns its input argument'
    return anything

  back