>>> def sub(arg1, arg2):
result = arg1 - arg2
return result
>>> sub(10, 15)
-5
The variable result is local, meaning that it is not
accessible to the main Python script, and it is used only
within the function itself. If you tried to call result
directly, Python would produce an error saying that
result is not defined. You can, however, access global
variables from within the function; you might do this, for
example, to set certain constants or key variables that
any function can use (for example, IP addresses). The
difference in accessibility between a local variable and
global variable is important, because they allow your
code to maintain separation and can keep your functions
self-contained.
The previous example uses positional arguments, which
must be passed to a function in a particular order.
Positional arguments work with a simple set of
consistently applied arguments, but if a function needs
more flexible alignment to parameters within a function,
you can use keyword arguments instead. A keyword
argument is a name/value pair that you pass to a
function. Instead of using position, you specify the
argument the function uses. It is a lot like assigning a
variable to an argument. In the previous example, arg1 is
subtracted from arg2, and if the positions of these
arguments were switched, you would get a different
result when subtracting the values. With keyword
arguments, it doesn’t matter in what order they are
passed to the function. Here is an example:
>>> sub(arg2=15, arg1=10)
-5