Creating Functions - Lesson 7

Questions

  • How can I define new functions?
  • What’s the difference between defining and calling a function?
  • What happens when I call a function?

Objectives

  • Define a function that takes parameters.
  • Return a value from a function.
  • Set default values for function parameters.
  • Document our functions.
  • Explain why we should divide programs into small, single-purpose functions.

Lecture



Alternate video link.


Jupyter Notebook File

Please use the Jupyter notebook named "07CreatingFunctions.ipynb" for this lesson. If you haven't downloaded them already, you may find them here.

Key Points

  • Define a function using def function_name(parameter).
  • The body of a function must be indented.
  • Call a function using function_name(value).
  • Numbers are stored as integers or floating-point numbers.
  • Variables defined within a function can only be seen and used within the body of the function.
  • If a variable is not defined within the function it is used, Python looks for a definition before the function call
  • Use help(thing) to view help for something.
  • Put docstrings in functions to provide help for that function.
  • Specify default values for parameters when defining a function using name=value in the parameter list.
  • Parameters can be passed by matching based on name, by position, or by omitting them (in which case the default value is used).