Python Functions
1. Introduction to Functions
- 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.
2. Defining a Function
- Use the 'def' keyword to define a function.
- Syntax: def function_name(parameters):
3. Calling a Function
- Call a function using its name followed by parentheses.
- Example: function_name()
4. Function Arguments
- Positional Arguments
- Keyword Arguments
- Default Parameters
- Arbitrary Arguments (*args)
- Arbitrary Keyword Arguments (**kwargs)
5. Return Statement
- Use the 'return' keyword to return a value from a function.
- You can return multiple values as a tuple.
6. Scope of Variables
- Local Variables
- Global Variables
- The 'global' Keyword
7. Lambda Functions
- Anonymous functions defined with the 'lambda' keyword.
- Syntax: lambda arguments: expression
- Used for small, throwaway functions.
8. Recursive Functions
- A function that calls itself.
- Used for tasks that can be divided into similar sub-tasks.
9. Docstrings
- Used to document functions.
- Placed as the first statement in a function body using triple quotes.
10. Best Practices
- Use descriptive names for functions.
- Keep functions short and focused on a single task.
- Write reusable and testable code.
- Use type hints for clarity.