# Python Programming/Functions

This lesson introduces functions.

## Objectives and Skills

Objectives and skills for this lesson include:
* Functions
** Function parameters and local variables
** Using global and nonlocal statement
** Default Argument values and keyword arguments
** VarArgs and keyword-only parameters
** The return statement
** DocStrings and annotations

## Readings

* Wikipedia: Function (computer science)
* Wikipedia: Parameter (computer programming)
* Wikipedia: Recursion (computer science)
* Python for Everyone: Functions

## Multimedia

* YouTube: Python for Informatics - Chapter 4 - Functions
* YouTube: Python Functions
* YouTube: Python Return Values
* YouTube: Variable Scope
* YouTube: Default Values for Arguments
* YouTube: Keyword Arguments
* YouTube: Flexible Number of Arguments
* YouTube: Python 3 Programming Tutorial - Function Parameters
* YouTube: Python 3.5 Tutorial - Explaining The DocString
* YouTube: How To Use Functions In Python (Python Tutorial #3)

## Examples
### Built-In Functions

The Python interpreter has a number of functions and types built into it that are always available.

### User-Defined Functions

A function definition defines a user-defined function object. If specified, return leaves the current function call with the expression list (or None) as return value.
Output:

### Local Variables

If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Output:

### Global Variables

Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Output:

### Nonlocal Variables

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
Output:

### Parameters

A parameter is a named entity in a function definition that specifies an argument that the function can accept. Functions may specify a default value for one or more arguments. Functions may also be called using keyword arguments rather than positional arguments.
Output:

### Parameter Validation

According to the Zen of Python, errors should never pass silently. Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.

### Assertions

An assertion is a statement that a true–false expression is expected to always be true at that point in the code. The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when optimization is requested (using command line option -O).

### Variable Arguments

Functions may accept a variable number of arguments using the * operator. The variable arguments are provided as a Python list. See Python Programming/Lists for more information.
Output:

### Variable Named Arguments

Variable named arguments may be accessed using the ** operator. The variable named arguments are provided as a Python dictionary. See Python Programming/Dictionaries for more information.
Output:

### Docstring

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.
Output:

### Recursion Example

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Output:

## Activities
### Tutorials

* Complete one or more of the following tutorials:
** LearnPython
*** Functions
** TutorialsPoint
*** Functions
** Codecademy
*** Functions
** Wikiversity
*** Python/Functions
** Wikibooks
*** Wikibooks: A Beginner's Python Tutorial/Functions

### Practice

* Review Python.org: Built-in Functions. Create a Python program that asks the user for a numeric input value. Demonstrate the use of a variety of built-in functions by displaying the input value's initial type (type). Then convert and display the input value as an integer (int), a float (float), and a Boolean (bool). Use the converted integer to display the value as a character (chr), and in binary (bin), octal (oct), and hexadecimal (hex) format. Use the converted float to display the value rounded to no decimal places (round), and formatted as currency with two decimal places (format). Include try and except to handle input errors. Test the program with both integer and floating point values.
* Create a Python program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Display their approximate age in the selected timeframe. Include try and except to handle input errors.
* Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Calculate and display the converted temperature. Include try and except to handle input errors.
* Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Include try and except to handle input errors.
* Review MathsIsFun: Greatest Common Factor. Create a Python program that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result. Include try and except to handle input errors.

## Lesson Summary
### Function Concepts

* A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
* In different programming languages, a function may be called a procedure, a subroutine, a routine, a method, or a subprogram.
* A function is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other functions, and then branch back (return) to the next instruction after the call once the function's task is done.
* The content of a function is its body, the piece of program code that is executed when the function is called or invoked.
* A function may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.
* Function arguments may be passed using call-by-reference or call-by-value.
* A function may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
* A function can be coded so that it may call itself recursively, at one or more places, to perform its task.
* The advantages of breaking a program into functions include:
** decomposing a complex programming task into simpler steps
** reducing duplicate code within a program
** enabling reuse of code across multiple programs
** hiding implementation details from users of the function
* With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).
* With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
* Some programming languages allow for a default argument to be explicitly or implicitly given in a subroutine's declaration.
* Some languages allow functions to be defined to accept a variable number of arguments. For such languages, the functions must iterate through the list of arguments.
* Some programming languages allow functions to have named parameters.

### Python Functions

* A Python function definition defines a user-defined function object. The basic syntax for declaring a function is: def <name>([parameters]): <statements>
* Python arguments are passed using call by value.
* By default, Python arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
* A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).
* The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.
* Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.
* The Python interpreter has a number of functions and types built into it that are always available.
* A function definition defines a user-defined function object. If specified, return leaves the current function call with the expression list (or None) as return value.
* If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
* Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
* The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
* A parameter is a named entity in a function definition that specifies an argument that the function can accept. Functions may specify a default value for one or more arguments. Functions may also be called using keyword arguments rather than positional arguments.
* Errors should never pass silently.
* Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.
* An assertion is a statement that a true–false expression is expected to always be true at that point in the code.
* The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when when optimization is requested (using command line option -O).
* Functions may accept a variable number of arguments using the * operator. The variable arguments are provided as a Python list.
* Variable named arguments may be accessed using the ** operator. The variable named arguments are provided as a Python dictionary.
* A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.

## Key Terms
### algorithm

    A general process for solving a category of problems.

### argument

    A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.

### body

    The sequence of statements inside a function definition.

### composition

    Using an expression as part of a larger expression, or a statement as part of a larger statement.

### deterministic

    Pertaining to a program that does the same thing each time it runs, given the same inputs.

### dot notation

    The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.

### flow of execution

    The order in which statements are executed during a program run.

### fruitful function

    A function that returns a value.

### function

    A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.

### function call

    A statement that executes a function. It consists of the function name followed by an argument list.

### function definition

    A statement that creates a new function, specifying its name, parameters, and the statements it executes.

### function object

    A value created by a function definition. The name of the function is a variable that refers to a function object.

### header

    The first line of a function definition.

### import statement

    A statement that reads a module file and creates a module object.

### module object

    A value created by an import statement that provides access to the data and code defined in a module.

### parameter

    A name used inside a function to refer to the value passed as an argument.

### pseudorandom

    Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.

### return value

    The result of a function. If a function call is used as an expression, the return value is the value of the expression.

### void function

    A function that does not return a value.

## Review Questions

* A function or subroutine is _____. A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
* In different programming languages, a function may be called a _____, a _____, a _____, a _____, or a _____. In different programming languages, a function may be called a procedure, a subroutine, a routine, a method, or a subprogram.
* A function is often coded so that _____. A function is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other functions, and then branch back (return) to the next instruction after the call once the function's task is done.
* The content of a function is _____. The content of a function is its body, the piece of program code that is executed when the function is called or invoked.
* A function may be written so that it expects to obtain one or more data values from _____. A function may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.
* Function arguments may be passed using _____ or _____. Function arguments may be passed using call-by-reference or call-by-value.
* A function may also return _____. A function may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
* A function can be coded so that it may call itself _____, at one or more places, to perform its task. A function can be coded so that it may call itself recursively, at one or more places, to perform its task.
* The advantages of breaking a program into functions include: The advantages of breaking a program into functions include: decomposing a complex programming task into simpler steps reducing duplicate code within a program enabling reuse of code across multiple programs hiding implementation details from users of the function
* With call by value, a parameter acts within the subroutine as _____. With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).
* With call by reference, the argument supplied by the caller _____. With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
* Some programming languages allow for a default argument to be _____. Some programming languages allow for a default argument to be explicitly or implicitly given in a subroutine's declaration.
* Some languages allow functions to be defined to accept a _____. Some languages allow functions to be defined to accept a variable number of arguments. For such languages, the functions must iterate through the list of arguments.
* Some programming languages allow functions to have _____ parameters. Some programming languages allow functions to have named parameters.
* A Python function definition defines a user-defined function object. The basic syntax for declaring a function is: A Python function definition defines a user-defined function object. The basic syntax for declaring a function is: def <name>([parameters]):  <statements>
* Python arguments are passed using call by _____. Python arguments are passed using call by value.
* By default, Python arguments are passed by _____. By default, Python arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
* A recursive function definition has _____. A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).
* The job of the recursive cases can be seen as _____. The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.
* Recursive programming solutions include _____. Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.
* The Python interpreter has a number of functions and types _____. The Python interpreter has a number of functions and types built into it that are always available.
* A function definition defines _____. A function definition defines a user-defined function object. If specified, return leaves the current function call with the expression list (or None) as return value.
* If a variable is assigned a value anywhere within the function’s body, it’s assumed to be _____. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
* Variables that are only referenced inside a function are implicitly _____. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a _____. Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
* The nonlocal statement causes the listed identifiers to _____. The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
* A parameter is _____. A parameter is a named entity in a function definition that specifies an argument that the function can accept. Functions may specify a default value for one or more arguments. Functions may also be called using keyword arguments rather than positional arguments.
* Errors should _____. Errors should never pass silently.
* Parameter validation is _____. Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.
* An assertion is _____. An assertion is a statement that a true–false expression is expected to always be true at that point in the code.
* The assert statement _____. The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when when optimization is requested (using command line option -O).
* Functions may accept a variable number of arguments using _____. Functions may accept a variable number of arguments using the * operator. The variable arguments are provided as a Python list.
* Variable named arguments may be accessed using _____. Variable named arguments may be accessed using the ** operator. The variable named arguments are provided as a Python dictionary.
* A docstring is _____. A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.

## Assessments

* Flashcards: Quizlet: Python Functions
* Quiz: Quizlet: Python Functions

## See Also

* Python.org: More Control Flow Tools
* SoloLearn: Python
* DotNetPerls: Python global and nonlocal
* Python.org: Docstring Conventions
* Open Book Project: Python 3 - Functions
* Open Book Project: Python 3 - Fruitful Functions
* Python For Beginners: Functions
* DataCamp: Python Functions Tutorial