|
|
|
|
|
Lesson 4: Python Functions
- Functions provide the options of code reuse and decomposition of programs into managable parts [ 4, 2: 98]. In Python, function definitions have the syntax:
def identifier (argument_1, argument_2, ..., argument_n):- # Do something
- return value
- The def reserved word defines the function and the return reserved word sends a value back to the calling procedure. Functions are not required to have a return value. Therefore, the return
is optional. List and dictionary arguments are passed by
reference, meaning that any change to their values remains after the
function terminates. All other variable types are passed by
value, and changes made to the variables are not carried beyond the
local scope of the function.
- Function calls have the syntax:
value = identifier(argument_1, argument_2, ..., argument_n)
- Typically,
arguments are passed as positionals, and are matched left to
right. They can be passed as keywords with the function arguments
assigned to formal parameters in the function call. Additionly,
arguments can be omitted if the function definition supplies default
values. Code Example 4.1 demonstrates the typical variations of
function calls.
A Note on Variable Scope
- Variables
in Python can have one of three scopes: local, global, and
built-in. Local variables are specific to their functions.
Global variables are accessible anywhere in a program. Built-in
variables are those defined in the Python language. An important aspect
of scope in Python is that local names are detected statically.
This means that a undefined local variable is not looked up in the
calling procedure; it obtains its definition from the enclosing module [2: 117].
Code Example 4.2 demonstrates this feature.
- Note that the Python interpreter did not look up the value of gender dynamically at runtime from the calling procedure. Instead, it found the value of gender by recursing the static chain of the compiled code, and therefore selected the logically incorrect value.
To Lesson 5 ...
|
|