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

 * 1)  Function (computer science)
 * 2)  Parameter (computer programming)
 * 3)  Recursion (computer science)
 * 4) Python for Everyone: Functions

Multimedia

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

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: In function_1 In function_2 with parameter value: test In function_3 with parameter value: test function_3 returned testtest

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: Local value: 1 Cannot access local variable. Parameter value: 1 Parameter value: 2 Global value: 1

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: Global value: 1 Global value: 2 Global value: 2

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

Output: Global value: 3 Function value: 4

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: x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 8 y = 7

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: 10

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: ('y', 2) ('x', 1)

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: This docstring documents the function, describes the parameter requirements, etc.

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: 5! = 120

Tutorials

 * 1) Complete one or more of the following tutorials:
 * 2) * LearnPython
 * 3) ** Functions
 * 4) * TutorialsPoint
 * 5) ** Functions
 * 6) * Codecademy
 * 7) ** Functions
 * 8) * Wikiversity
 * 9) ** Python/Functions
 * 10) * Wikibooks
 * 11) ** A Beginner's Python Tutorial/Functions

Practice

 * 1) 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.
 * 2) 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.
 * 3) 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.
 * 4) 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.
 * 5) 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  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.

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:
 * 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.

Assessments

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