๐ง Python Functions and Functional Programming โ Complete Guide (2025)
๐งฒ Introduction โ Why Learn Python Functions?
Functions are the building blocks of modular, reusable, and efficient Python programs. Pythonโs flexible function model supports traditional, functional, and advanced programming techniques like closures, decorators, and higher-order functions.
๐ฏ In this guide, youโll learn:
- How to define and call functions in Python
- Different argument types and return values
- Functional concepts like lambda, recursion, closures, and decorators
๐ Topics Covered
| ๐ข Topic | ๐ Description | 
|---|---|
| Python Functions | Defining and calling reusable blocks of code | 
| Python Default Arguments | Assigning default values to function parameters | 
| Python Keyword Arguments | Passing arguments by name | 
| Python Positional Arguments | Arguments passed in order | 
| Python Arbitrary Arguments | Handling unknown number of arguments using *args/**kwargs | 
| Positional-Only & Keyword-Only Args | Enforcing how arguments must be passed (Python 3.8+) | 
| Python Return Statement | Returning results from functions | 
| Python Recursion | Functions that call themselves | 
| Python Lambda Functions | Anonymous, inline functions | 
| Python Function Annotations | Metadata for parameters and return types | 
| Python Scope (LEGB Rule) | Variable visibility rules inside and outside functions | 
| Python Closures | Functions that remember their lexical scope | 
| Python Decorators | Modifying functions using wrapper functions | 
| Python Higher Order Functions | Functions that accept or return other functions | 
๐ง Python Functions โ Basic Definition
A function is defined using the def keyword:
def greet(name):
    print("Hello", name)
    
greet("Alice")
Functions make code reusable, readable, and organized.
๐ฏ Python Default Arguments
Provide fallback values if arguments arenโt passed:
def greet(name="Guest"):
    print("Hello", name)
greet()          # Hello Guest
greet("Alice")   # Hello Alice
๐ Python Keyword Arguments
Specify argument names during a function call:
def student(name, age):
    print(name, age)
student(age=20, name="John")
Order doesnโt matter when using keywords.
๐ Python Positional Arguments
Arguments passed in the order they appear:
def add(a, b):
    return a + b
print(add(5, 3))  # 8
โจ Python Arbitrary Arguments โ *args and **kwargs
For variable-length arguments:
def fruits(*args):
    for item in args:
        print(item)
fruits("apple", "banana", "cherry")
def user_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
user_info(name="Alice", age=30)
๐๏ธ Positional-Only and Keyword-Only Arguments (Python 3.8+)
Use / and * to enforce argument passing styles:
def example(a, /, b, *, c):
    print(a, b, c)
example(1, b=2, c=3)  # Valid
- /before args โ positional-only
- *after args โ keyword-only
๐ Python Return Statement
Functions can return values using return.
def square(x):
    return x * x
result = square(4)
print(result)  # 16
๐ Python Recursion
Function calling itself repeatedly:
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
print(factorial(5))  # 120
Use recursion with care to avoid stack overflow.
โก Python Lambda Functions
Anonymous one-liner functions:
square = lambda x: x * x
print(square(5))  # 25
Often used with functions like map(), filter(), sorted().
๐ท๏ธ Python Function Annotations
Annotate function parameters and return type:
def greet(name: str) -> str:
    return "Hello " + name
Annotations are not enforced by Python but useful for tools and readability.
๐ Python Scope โ LEGB Rule
Python uses the LEGB rule for variable resolution:
- Local โ inside current function
- Enclosing โ enclosing function scope (closures)
- Global โ top-level script variables
- Built-in โ Pythonโs built-in names (like print)
Example:
x = "global"
def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)
    inner()
outer()
๐ง Python Closures
A closure remembers variables from enclosing scopes:
def outer():
    msg = "Hello"
    def inner():
        print(msg)
    return inner
greet = outer()
greet()  # Hello
Useful for decorators and encapsulated logic.
๐ Python Decorators
A decorator is a function that modifies another function.
def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper
@decorator
def say_hello():
    print("Hello!")
say_hello()
Used in logging, authorization, timing, etc.
๐ Python Higher Order Functions
Functions that take other functions as arguments or return them.
def apply(f, x):
    return f(x)
print(apply(lambda x: x*x, 5))  # 25
Supports functional paradigms like map(), reduce(), etc.
๐ Summary โ Recap & Next Steps
Pythonโs function system is versatileโfrom simple def statements to advanced decorators and lambdas. Mastering these tools helps build cleaner, more powerful, and scalable codebases.
๐ Key Takeaways:
- Use def,return, and flexible arguments (*args,**kwargs)
- Leverage recursion and lambdas for concise logic
- Use decorators and closures for modular enhancements
- Understand function scope through the LEGB rule
โ๏ธ Next Steps:
- Build projects using reusable functions
- Explore the functoolsmodule for built-in decorators
- Study functional libraries like toolzoritertools
โ Frequently Asked Questions (FAQs)
โ What is the difference between *args and **kwargs?
โ
 *args collects positional arguments as a tuple, **kwargs collects keyword arguments as a dictionary.
โ Can Python functions return multiple values?
โ
 Yes. Return as tuple:
def info():
    return "Alice", 30
name, age = info()
โ What are closures used for?
โ
 Closures are used to retain state between function calls and are often used in decorators.
โ When should I use lambda functions?
โ
 Use them for short, throwaway functions, especially with map(), filter(), or sorted().
โ How do decorators work in Python?
โ
 They wrap another function to add or modify behavior without changing its code.
Share Now :
