Introduction to Python: Functions

Introduction to Python: Functions

Functions are organized, reusable code blocks that implement a single or related functionality.

Functions enhance the modularity of applications and the reusability of code. Python provides many built-in functions, such as print(). However, you can also create your own functions, known as user-defined functions.

Table of Contents

  1. 1. What is a Function
  2. 2. Defining and Calling Functions
  3. 3. Function Parameters
  • Required Parameters
  • Default Parameters
  • Variable Parameters *args
  • Keyword Parameters **kwargs
  • Parameter Order
  • 4. Return Values
  • 5. Local and Global Variables
  • 6. Anonymous Functions (lambda)
  • 7. Built-in Functions
  • 1. What is a Function

    A function is a well-organized, reusable code block used to implement specific functionality.The benefits of functions include:

    • • Enhancing code reusability
    • • Improving code readability and maintainability

    Functions in Python are defined using the <span>def</span> keyword.

    2. Defining and Calling Functions

    Defining a Function

    def function_name(parameter_list):
        """Function documentation (optional)"""
        function_body
        return return_value

    Calling a Function

    function_name(arguments)

    Example:

    def greet(name):
        """Greeting function"""
        return f"Hello, {name}!"
    
    print(greet("Alice"))

    3. Function Parameters

    3.1 Required Parameters

    Parameters that must be passed when calling the function.

    def add(x, y):
        return x + y
    
    print(add(2, 3))  # Outputs 5

    3.2 Default Parameters

    Parameters that have default values set during function definition and can be omitted when calling.

    def greet(name="World"):
        print(f"Hello, {name}!")
    
    greet()         # Outputs Hello, World!
    greet("Alice")  # Outputs Hello, Alice!

    3.3 Variable Parameters *args

    Use <span>*args</span> to accept multiple positional arguments, resulting in a tuple.

    def sum_numbers(*args):
        return sum(args)
    
    print(sum_numbers(1, 2, 3, 4))  # Outputs 10

    3.4 Keyword Parameters **kwargs

    Use <span>**kwargs</span> to accept multiple keyword arguments, resulting in a dictionary.

    def show_info(**kwargs):
        for k, v in kwargs.items():
            print(k, ":", v)
    
    show_info(name="Alice", age=18)

    3.5 Parameter Order

    The order of parameter definitions is: **Required Parameters → Default Parameters → *args → kwargs

    4. Return Values

    • • Use <span>return</span> to return results
    • • If there is no <span>return</span>, the function defaults to returning <span>None</span>
    def square(x):
        return x * x
    
    print(square(5))  # Outputs 25

    5. Local and Global Variables

    • • Variables defined inside a function are local variables and are only valid within that function
    • • Variables defined outside a function are global variables and are valid throughout the entire program
    • • If you need to modify a global variable within a function, you must declare it using the <span>global</span> keyword
    x = 10
    
    def change():
        global x
        x = 20
    
    change()
    print(x)  # Outputs 20

    6. Anonymous Functions (lambda)

    Anonymous functions are defined using <span>lambda</span> and have a simple syntax. Syntax:<span>lambda parameters: expression</span>

    square = lambda x: x * x
    print(square(5))  # Outputs 25

    Commonly used for: sorting, filtering, simple calculations, etc.

    7. Built-in Functions

    Python provides a large number of built-in functions, commonly used ones include:

    • <span>len()</span>: Get length
    • <span>type()</span>: Check data type
    • <span>range()</span>: Generate a sequence of numbers
    • <span>max() / min()</span>: Maximum / Minimum value
    • <span>sum()</span>: Sum
    • <span>sorted()</span>: Sort

    Conclusion

    • Function Definition: <span>def</span> keyword
    • Parameter Types: Required Parameters, Default Parameters, <span>*args</span>, <span>**kwargs</span>
    • Return Values: Use <span>return</span> to return results
    • Scope: Local Variables / Global Variables
    • Anonymous Functions: <span>lambda</span>
    • Built-in Functions: Python’s built-in utility functions

    Leave a Comment