Python Programming/Functions
This lesson introduces functions.
Objectives and Skills
editObjectives 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
editMultimedia
edit- 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
editBuilt-In Functions
editThe 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
editA 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
editIf 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
editVariables 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
editThe 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
editA 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
editAccording 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
editAn 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
editFunctions 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
editVariable 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
editA 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
editThe 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
editTutorials
edit- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
edit- 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
editFunction 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-
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
edit- Flashcards: Quizlet: Python Functions
- Quiz: Quizlet: Python Functions
See Also
editReferences
edit- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Function definitions
- ↑ Python.org: The return statement
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Nonlocal
- ↑ Python.org: Programming FAQ
- ↑ Python.org: Parameter
- ↑ Python.org: More flow control tools
- ↑ Python.org: More flow control tools
- ↑ Python.org: The Zen of Python
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Assertion (software development)
- ↑ Python.org: The assert statement
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonTips: args and kwargs explained
- ↑ TutorialsPoint: Python Dictionary
- ↑ Python.org: Docstring Conventions
- ↑ Python.org: Documentation Strings
- ↑ Wikipedia: Factorial
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Python.org: Function definitions
- ↑ Python.org: Defining Functions
- ↑ Python.org: Keyword Arguments
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Function definitions
- ↑ Python.org: The return statement
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Nonlocal
- ↑ Python.org: Programming FAQ
- ↑ Python.org: Parameter
- ↑ Python.org: More flow control tools
- ↑ Python.org: More flow control tools
- ↑ Python.org: The Zen of Python
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Assertion (software development)
- ↑ Python.org: The assert statement
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonTips: args and kwargs explained
- ↑ TutorialsPoint: Python Dictionary
- ↑ Python.org: Docstring Conventions
- ↑ Python.org: Documentation Strings
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions