Python Functions¶
Functions: Reusable Code Blocks¶
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
Why use Functions?¶
- Reusability: Define code once, and use it many times.
- Organization: Break down large programs into smaller, manageable pieces.
- Abstraction: You don't need to know how the function works, just what it does (like a remote control).
Components of a Function¶
- Definition: Creating the function.
- Arguments/Parameters: The information you send into the function.
- Body: The code that performs the task.
- Return Value: The result the function sends back.
Logic First
Think of a function like a recipe. The recipe is the definition; the ingredients are the parameters; the cooking is the body; and the finished dish is the return value.
Creating a Function¶
In Python, a function is defined using the def keyword:
Calling a Function¶
To call a function, use the function name followed by parenthesis:
Arguments (Parameters)¶
Information can be passed into functions as arguments.
Return Values¶
To let a function return a value, use the return statement:
The *args and **kwargs¶
*args: If you do not know how many arguments will be passed into your function.**kwargs: If you do not know how many keyword arguments will be passed.
Global vs Local Variables
Variables created inside a function are local and cannot be used outside. Variables created outside are global.