Python Functions: A Complete Guide from Basics to Advanced

    Master Python functions with our comprehensive guide covering definitions, arguments, returns, lambda, decorators, and best practices.

    PE

    PythonExecutor Team

    8 min read

    On this page

    What is a Function?

    A function is a reusable block of code that performs a specific task. Functions help you:

    • Write DRY (Don't Repeat Yourself) code
    • Organize complex logic
    • Make code maintainable
    • Enable code reuse

    Defining Functions

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

    Function Arguments

    Positional Arguments

    def add(a, b):
        return a + b

    Default Arguments

    def power(base, exp=2):
        return base ** exp
    
    print(power(5))      # 25 (uses default exp=2)
    print(power(2, 10))  # 1024

    Keyword Arguments

    def describe(name, age, city="Unknown"):
        return f"{name}, {age}, from {city}"
    
    print(describe(age=30, name="Bob"))

    Variable Arguments (*args, **kwargs)

    def report(*args, **kwargs):
        print("Positional:", args)
        print("Keyword:", kwargs)

    Return Values

    Functions can return single or multiple values:

    def get_coordinates():
        return 10, 20  # Returns tuple
    
    x, y = get_coordinates()

    Lambda Functions

    Anonymous functions for simple operations:

    square = lambda x: x * x
    print(square(5))  # 25
    
    nums = [1, 2, 3, 4]
    squared = list(map(lambda n: n ** 2, nums))

    Best Practices

    1. Use clear names: calculate_total not calc
    2. Single responsibility: Function does one thing
    3. Document with docstrings: Explain what it does
    4. Keep functions small: Under 20 lines ideally
    5. Use type hints: Help others understand types
    def add(a: int, b: int) -> int:
        """Add two numbers and return the result."""
        return a + b

    Try it yourself

    The best way to learn is to run the code. Paste any example from this article into the free online Python playground, or test what you know with a coding challenge.

    All articles