Skip to main content

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 def keyword.

2. Defining a Function

  • Use the def keyword 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 return statement to send a value back to the caller.
Syntax:
Example:

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.
Example:

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.
Example:

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.
    Example:

6. Return Values

  • The return statement is used to send a value back to the caller.
  • A function can return multiple values as a tuple.
Example:

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 global keyword to modify a global variable inside a function.
Example:

8. Lambda Functions (Anonymous Functions)

  • Lambda functions are small, anonymous functions defined using the lambda keyword.
  • They can have any number of arguments but only one expression.
Syntax:
Example:

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.