1. What is a Function?
- A function is a reusable block of code that performs a specific task.
- Functions help in organizing code, reducing redundancy, and improving readability.
- In Python, functions are defined using the
defkeyword.
2. Defining a Function
- Use the
defkeyword followed by the function name and parentheses(). - Parameters (inputs) can be included inside the parentheses.
- The function body is indented and contains the code to be executed.
- Use the
returnstatement to send a value back to the caller.
3. Calling a Function
- To use a function, you need to call it by its name followed by parentheses
(). - If the function has parameters, pass the required arguments inside the parentheses.
4. Function Parameters and Arguments
- Parameters: Variables listed inside the parentheses in the function definition.
- Arguments: Values passed to the function when it is called.
5. Types of Arguments
-
Positional Arguments: Arguments are passed in the order of parameters.
-
Keyword Arguments: Arguments are passed with the parameter name.
-
Default Arguments: Parameters have default values if no argument is provided.
-
Variable-Length Arguments:
*args: Accepts any number of positional arguments as a tuple.**kwargs: Accepts any number of keyword arguments as a dictionary.
6. Return Values
- The
returnstatement is used to send a value back to the caller. - A function can return multiple values as a tuple.
7. Scope of Variables
- Local Variables: Variables defined inside a function are local to that function.
- Global Variables: Variables defined outside a function can be accessed globally.
- Use the
globalkeyword to modify a global variable inside a function.
8. Lambda Functions (Anonymous Functions)
- Lambda functions are small, anonymous functions defined using the
lambdakeyword. - They can have any number of arguments but only one expression.
9. Additional Examples
-
Simple Function:
-
Function with Default Argument:
-
Function with Variable-Length Arguments:
-
Lambda Function:
10. Best Practices
- Use descriptive function names to indicate their purpose.
- Keep functions small and focused on a single task.
- Use comments to explain complex logic.
- Avoid using too many global variables.