Python Tutorial
Estimated reading: 4 minutes 41 views

๐Ÿง  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 FunctionsDefining and calling reusable blocks of code
Python Default ArgumentsAssigning default values to function parameters
Python Keyword ArgumentsPassing arguments by name
Python Positional ArgumentsArguments passed in order
Python Arbitrary ArgumentsHandling unknown number of arguments using *args / **kwargs
Positional-Only & Keyword-Only ArgsEnforcing how arguments must be passed (Python 3.8+)
Python Return StatementReturning results from functions
Python RecursionFunctions that call themselves
Python Lambda FunctionsAnonymous, inline functions
Python Function AnnotationsMetadata for parameters and return types
Python Scope (LEGB Rule)Variable visibility rules inside and outside functions
Python ClosuresFunctions that remember their lexical scope
Python DecoratorsModifying functions using wrapper functions
Python Higher Order FunctionsFunctions 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:

  1. Local โ†’ inside current function
  2. Enclosing โ†’ enclosing function scope (closures)
  3. Global โ†’ top-level script variables
  4. 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 functools module for built-in decorators
  • Study functional libraries like toolz or itertools

โ“ 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿง  Python Functions and Functional Programming

Or Copy Link

CONTENTS
Scroll to Top