Python User-Defined Functions
- A function is a set of statements that perform a specific task, a common structuring element that allows you to use a piece of code repeatedly in different parts of a program. The use of functions improve a program’s clarity and comprehensibility and makes programming more efficient by reducing code duplication and breaking down complex tasks into more manageable pieces.
- Functions are also known as routines, subroutines, methods, procedures, or subprograms.
- They can be passed as arguments, assigned to variables, or stored in collections.
- A user-defined Python function is created or defined by the def statement.
def function_name(parameter list):
The indented statements make up the body of the function and are executed when the function is called. Once the function is called, parameters inside round brackets become arguments.
if number >= 0:
//In the above example, number is the parameter of the function absolute_value. It acts as a variable name and holds the value of a passed in argument.
Functions can call other functions
Functions can perform different types of actions such as do simple calculations and print text. They can also call another function.
return n * 3
return members_total(m) + 5
Scope and lifetime of a local variable
- A variable’s scope refers to a program’s sections where it is recognized.
- Variables and parameters defined within a function have a local scope and are not visible from outside of the function.
- On the other hand, a variable’s lifetime refers to its period of existence in the memory.
- Its lifetime coincides with the execution of a function which ends when you return from the function.
- A variable’s value is discarded once the return is reached and a function won’t be able to recall a variable’s value from its previous value.