Python Programming/Functions

This lesson introduces functions.

Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

  • 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

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

Multimedia

edit
  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)

Examples

edit

Built-In Functions

edit

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

value = 65
print(bin(value))    # 0b1000001
print(oct(value))    # 0o101
print(hex(value))    # 0x41
print(chr(value))    # A

value = 1234.567
print(round(value, 1))          # 1234.6
print(format(value, ",.2f"))    # 1,234.57

User-Defined Functions

edit

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

def function_1():
    print("In function_1")
    
def function_2(parameter):
    print("In function_2 with parameter value:", parameter)
    
def function_3(parameter):
    print("In function_3 with parameter value:", parameter)
    return(parameter * 2)
    
function_1()
function_2("test")
result = function_3("test")
print("function_3 returned", result)

Output:

In function_1
In function_2 with parameter value: test
In function_3 with parameter value: test
function_3 returned testtest

Local Variables

edit

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.[5]

def local_variable():
    value = 1
    print("Local value:", value)

def local_parameter(value):
    print("Parameter value:", value)
    value = 2
    print("Parameter value:", value)

local_variable()
try:
    print("value:", value)
except:
    print("Cannot access local variable.")
    
value = 1
local_parameter(value)
print("Global value:", value)

Output:

Local value: 1
Cannot access local variable.
Parameter value: 1
Parameter value: 2
Global value: 1

Global Variables

edit

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.[6]

def global_access():
    print("Global value:", value)

def global_modification():
    global value
    value = 2
    print("Global value:", value)

value = 1
global_access()
global_modification()
print("Global value:", value)

Output:

Global value: 1
Global value: 2
Global value: 2

Nonlocal Variables

edit

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.[7][8]

global_value = 1

def function():
    function_value = 2
    
    def nested_function():
        global global_value
        nonlocal function_value
        
        global_value = 3
        function_value = 4
    
    nested_function()
    print("Global value:", global_value)
    print("Function value:", function_value)

function()

Output:

Global value: 3
Function value: 4

Parameters

edit

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

def parameters(x = 1, y = 2):
    print("x =", x, "y =", y)
    
parameters()
parameters(3, 4)
parameters(5, 6)
parameters(y = 7, x = 8)

Output:

x = 1 y = 2
x = 3 y = 4
x = 5 y = 6
x = 8 y = 7

Parameter Validation

edit

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

def function(integer):
    if type(integer) is not int:
        raise TypeError("Parameter integer must be an integer.")

    if integer < 0:
        raise ValueError("Parameter integer must be greater than or equal to zero.")
    ...

Assertions

edit

An assertion is a statement that a true–false expression is expected to always be true at that point in the code.[14] 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).[15]

def function(integer):
    assert type(integer) is int
    assert integer >= 0
    ...

Variable Arguments

edit

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

def sum(*args):
    total = 0
    for arg in args:
        total += arg
    return total
    
print(sum(1, 2, 3, 4))

Output:

10

Variable Named Arguments

edit

Variable named arguments may be accessed using the ** operator.[17][18][19] The variable named arguments are provided as a Python dictionary. See Python Programming/Dictionaries for more information.

def keywords(**kwargs):
    for item in kwargs.items():
        print(item)

keywords(x = 1, y = 2)

Output:

('y', 2)
('x', 1)

Docstring

edit

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.[20][21]

def function(parameter):
    """This docstring documents the function, describes the parameter requirements, etc."""
    pass

print(function.__doc__)

Output:

This docstring documents the function, describes the parameter requirements, etc.

Recursion Example

edit

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

def factorial(value):
    """This function returns the factorial of the value provided using recursion."""

    if type(value) is not int:
        raise TypeError("Parameter value must be an integer.")

    if value < 0:
        result = 0
    elif value == 0:
        result = 1
    else:
        result = value * factorial(value - 1)
    return result

print("5! =", factorial(5))

Output:

5! = 120

Activities

edit

Tutorials

edit
  1. Complete one or more of the following tutorials:

Practice

edit
  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 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

edit

Function Concepts

edit
  • A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.[23]
  • In different programming languages, a function may be called a procedure, a subroutine, a routine, a method, or a subprogram.[24]
  • 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.[25]
  • The content of a function is its body, the piece of program code that is executed when the function is called or invoked.[26]
  • 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.[27]
  • Function arguments may be passed using call-by-reference or call-by-value.[28]
  • A function may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.[29]
  • A function can be coded so that it may call itself recursively, at one or more places, to perform its task.[30]
  • The advantages of breaking a program into functions include:[31]
    • 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).[32]
  • With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.[33]
  • Some programming languages allow for a default argument to be explicitly or implicitly given in a subroutine's declaration.[34]
  • 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.[35]
  • Some programming languages allow functions to have named parameters.[36]

Python Functions

edit
  • A Python function definition defines a user-defined function object. The basic syntax for declaring a function is:[37]
    def <name>([parameters]):
        <statements>
  • Python arguments are passed using call by value.[38]
  • By default, Python arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[39]
  • 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).[40]
  • 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.[41]
  • Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.[42]
  • The Python interpreter has a number of functions and types built into it that are always available.[43]
  • A function definition defines a user-defined function object.[44] If specified, return leaves the current function call with the expression list (or None) as return value.[45]
  • 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.[46]
  • 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.[47]
  • The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.[48][49]
  • A parameter is a named entity in a function definition that specifies an argument that the function can accept.[50] Functions may specify a default value for one or more arguments.[51] Functions may also be called using keyword arguments rather than positional arguments.[52]
  • Errors should never pass silently.[53]
  • Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.[54]
  • An assertion is a statement that a true–false expression is expected to always be true at that point in the code.[55]
  • 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).[56]
  • Functions may accept a variable number of arguments using the * operator.[57] The variable arguments are provided as a Python list.
  • Variable named arguments may be accessed using the ** operator.[58][59][60] 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.[61][62]

Key Terms

edit
algorithm
A general process for solving a category of problems.[63]
argument
A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.[64]
body
The sequence of statements inside a function definition.[65]
composition
Using an expression as part of a larger expression, or a statement as part of a larger statement.[66]
deterministic
Pertaining to a program that does the same thing each time it runs, given the same inputs.[67]
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.[68]
flow of execution
The order in which statements are executed during a program run.[69]
fruitful function
A function that returns a value.[70]
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.[71]
function call
A statement that executes a function. It consists of the function name followed by an argument list.[72]
function definition
A statement that creates a new function, specifying its name, parameters, and the statements it executes.[73]
function object
A value created by a function definition. The name of the function is a variable that refers to a function object.[74]
header
The first line of a function definition.[75]
import statement
A statement that reads a module file and creates a module object.[76]
module object
A value created by an import statement that provides access to the data and code defined in a module.[77]
parameter
A name used inside a function to refer to the value passed as an argument.[78]
pseudorandom
Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.[79]
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.[80]
void function
A function that does not return a value.[81]

Review Questions

edit
Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. A function or subroutine is _____.
    A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. Function arguments may be passed using _____ or _____.
    Function arguments may be passed using call-by-reference or call-by-value.
  7. 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.
  8. 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.
  9. 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

  10. 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).
  11. 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.
  12. 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.
  13. 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.
  14. Some programming languages allow functions to have _____ parameters.
    Some programming languages allow functions to have named parameters.
  15. 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>

  16. Python arguments are passed using call by _____.
    Python arguments are passed using call by value.
  17. 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.
  18. 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).
  19. 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.
  20. Recursive programming solutions include _____.
    Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.
  21. 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.
  22. 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.
  23. 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.
  24. 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.
  25. 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.
  26. 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.
  27. Errors should _____.
    Errors should never pass silently.
  28. Parameter validation is _____.
    Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.
  29. 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.
  30. 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).
  31. 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.
  32. 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.
  33. 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

edit

See Also

edit

References

edit
  1. Vskills: Certified Python Developer
  2. Python.org: Built-in Functions
  3. Python.org: Function definitions
  4. Python.org: The return statement
  5. Python.org: Rules for local and global variables
  6. Python.org: Rules for local and global variables
  7. Python.org: Nonlocal
  8. Python.org: Programming FAQ
  9. Python.org: Parameter
  10. Python.org: More flow control tools
  11. Python.org: More flow control tools
  12. Python.org: The Zen of Python
  13. Wikipedia: Parameter validation
  14. Wikipedia: Assertion (software development)
  15. Python.org: The assert statement
  16. Python.org: More Flow Control Tools
  17. Python.org: More Flow Control Tools
  18. PythonTips: args and kwargs explained
  19. TutorialsPoint: Python Dictionary
  20. Python.org: Docstring Conventions
  21. Python.org: Documentation Strings
  22. Wikipedia: Factorial
  23. Wikipedia: Subroutine
  24. Wikipedia: Subroutine
  25. Wikipedia: Subroutine
  26. Wikipedia: Subroutine
  27. Wikipedia: Subroutine
  28. Wikipedia: Subroutine
  29. Wikipedia: Subroutine
  30. Wikipedia: Subroutine
  31. Wikipedia: Subroutine
  32. Wikipedia: Parameter (computer programming)
  33. Wikipedia: Parameter (computer programming)
  34. Wikipedia: Parameter (computer programming)
  35. Wikipedia: Parameter (computer programming)
  36. Wikipedia: Parameter (computer programming)
  37. Python.org: Function definitions
  38. Python.org: Defining Functions
  39. Python.org: Keyword Arguments
  40. Wikipedia: Recursion (computer science)
  41. Wikipedia: Recursion (computer science)
  42. Wikipedia: Recursion (computer science)
  43. Python.org: Built-in Functions
  44. Python.org: Function definitions
  45. Python.org: The return statement
  46. Python.org: Rules for local and global variables
  47. Python.org: Rules for local and global variables
  48. Python.org: Nonlocal
  49. Python.org: Programming FAQ
  50. Python.org: Parameter
  51. Python.org: More flow control tools
  52. Python.org: More flow control tools
  53. Python.org: The Zen of Python
  54. Wikipedia: Parameter validation
  55. Wikipedia: Assertion (software development)
  56. Python.org: The assert statement
  57. Python.org: More Flow Control Tools
  58. Python.org: More Flow Control Tools
  59. PythonTips: args and kwargs explained
  60. TutorialsPoint: Python Dictionary
  61. Python.org: Docstring Conventions
  62. Python.org: Documentation Strings
  63. PythonLearn: Functions
  64. PythonLearn: Functions
  65. PythonLearn: Functions
  66. PythonLearn: Functions
  67. PythonLearn: Functions
  68. PythonLearn: Functions
  69. PythonLearn: Functions
  70. PythonLearn: Functions
  71. PythonLearn: Functions
  72. PythonLearn: Functions
  73. PythonLearn: Functions
  74. PythonLearn: Functions
  75. PythonLearn: Functions
  76. PythonLearn: Functions
  77. PythonLearn: Functions
  78. PythonLearn: Functions
  79. PythonLearn: Functions
  80. PythonLearn: Functions
  81. PythonLearn: Functions