Python Programming/Functions: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Line 192: Line 192:
Output:
Output:
This docstring documents the function, describes the parameter requirements, etc.
This docstring documents the function, describes the parameter requirements, etc.
</pre>

=== Variable Arguments ===
Functions may accept a variable number of arguments using the * operator.<ref>[https://docs.python.org/3/tutorial/controlflow.html Python.org: More Flow Control Tools</ref>

<source lang="Python">
def sum(*args):
total = 0
for arg in args:
total += arg
return total
print(sum(1, 2, 3, 4))
</source>

<pre>
Output:
10
</pre>

=== Variable Named Arguments ===
Variable named arguments may be accessed using the ** operator.<ref>[https://docs.python.org/3/tutorial/controlflow.html Python.org: More Flow Control Tools</ref><ref>[https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ PythonTips: args and kwargs explained]</ref><ref>[http://www.tutorialspoint.com/python/python_dictionary.htm TutorialsPoint: Python Dictionary</ref> The variable arguments are provided as a Python dictionary. See [[Python Programming/Dictionaries]] for more information.

<source lang="Python">
def keywords(**kwargs):
for item in kwargs.items():
print(item)

keywords(x = 1, y = 2)
</source>

<pre>
Output:
('y', 2)
('x', 1)
</pre>
</pre>



Revision as of 16:17, 1 September 2016

This lesson introduces functions.

Objectives and Skills

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

  1. Wikipedia: Function (computer science)
  2. Wikipedia: Parameter (computer programming)
  3. Wikipedia: Recursion (computer science)
  4. PythonLearn:

Multimedia

  1. YouTube: Python for Informatics - Chapter 4 - Functions

Examples

Built-In Functions

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

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

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

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

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

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

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.[12][13]

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.

Variable Arguments

Functions may accept a variable number of arguments using the * operator.[14]

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

Variable Named Arguments

Variable named arguments may be accessed using the ** operator.[15][16][17] The variable 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)

Factorial

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

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

    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

Tutorials

  1. Complete one or more of the following tutorials:

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

Key Terms

algorithm
A general process for solving a category of problems.[19]
argument
A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.[20]
body
The sequence of statements inside a function definition.[21]
composition
Using an expression as part of a larger expression, or a statement as part of a larger statement.[22]
deterministic
Pertaining to a program that does the same thing each time it runs, given the same inputs.[23]
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.[24]
flow of execution
The order in which statements are executed during a program run.[25]
fruitful function
A function that returns a value.[26]
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.[27]
function call
A statement that executes a function. It consists of the function name followed by an argument list.[28]
function definition
A statement that creates a new function, specifying its name, parameters, and the statements it executes.[29]
function object
A value created by a function definition. The name of the function is a variable that refers to a function object.[30]
header
The first line of a function definition.[31]
import statement
A statement that reads a module file and creates a module object.[32]
module object
A value created by an import statement that provides access to the data and code defined in a module.[33]
parameter
A name used inside a function to refer to the value passed as an argument.[34]
pseudorandom
Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.[35]
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.[36]
void function
A function that does not return a value.[37]

See Also

References