What Are Functions in Python?

Functions are reusable blocks of code that perform specific tasks. They are essential for organizing code and improving efficiency.

function_definition

Key Concepts:

  • Function Declaration: Use def to define a function.
    def greet(name):
        return f"Hello, {name}!"
    
  • Function Call: Invoke a function with parentheses.
    greet("Alice")
    
  • Scope: Variables inside a function are local unless specified otherwise.
    function_scope

Types of Functions

1. Standard Functions

Regular functions defined with def.

2. Lambda Functions

Anonymous functions created with lambda.

lambda_function
Example: ```python add = lambda x, y: x + y ``` ### 3. **Built-in Functions** Predefined functions like `print()` or `len()`. ### 4. **Modules & Libraries** Use external libraries via `import` (e.g., `/en/resources/python-libraries` for more details).
import_statement

Parameters & Return Values

Parameters:

  • Positional arguments (required)
  • Keyword arguments (named)
  • Default arguments

Return Values:

Use return to output results.

return_statement
Example: ```python def calculate_area(radius): return 3.14 * radius ** 2 ```

Advanced Techniques

1. Decorators

Enhance functions with additional functionality.
Read more about decorators 📚

2. Closures

Functions that capture variables from outer scopes.

3. Recursion

Functions that call themselves.

recursion_example

Common Errors

  • Forgetting to include a colon after def
  • Incorrect indentation
  • Missing parentheses in function calls
  • Using return outside a function
    Explore Python error handling 🔍

For deeper insights into Python functions, check out our Python Basics Tutorial or Python Documentation. 📖