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.