Python Function Design

Description

๐Ÿ”ง Python Function - Full Concept Explained

๐Ÿ“˜ 1. Description

A Python Function is a block of reusable code that performs a specific task. Functions help you avoid repetition, make code modular, and improve readability.

It is defined using the def keyword followed by a name, parentheses (), and a colon :.

๐Ÿ” 2. Example


def greet(name):
    print(f"Hello, {name} ๐Ÿ‘‹!")

greet("Sairam")
    

๐ŸŽฏ 3. Why You Should Learn Functions?

  • ๐Ÿ” Reuse your code without repeating it.
  • ๐Ÿ“ฆ Keep your program modular and readable.
  • ๐Ÿงช Easier to test and debug.
  • ๐Ÿง  Build large applications efficiently.

๐Ÿงฐ 4. Use Cases (Tabular Format)

Use Case Description
Math Calculation Create functions like add(), subtract() to calculate numbers
API Handling Group all HTTP requests in functions (e.g., get_user_data())
File Operations Write functions to read/write files
Data Cleaning Use reusable functions to clean and format data
Email Notifications Send emails using a single function call

๐Ÿ“ฆ 5. Realtime Scenarios

  • โœ… Automate sending WhatsApp or email messages using a function.
  • ๐Ÿ“ˆ Read S3 files and apply a reusable parsing function to each file.
  • ๐Ÿ”„ Convert Excel to CSV with reusable conversion logic.
  • ๐Ÿงน Clean and validate user input using a function before saving to DB.
  • ๐Ÿ’ฌ Generate dynamic messages using template functions.

๐Ÿ“ 6. Practice Tests - Improve Your Function Skills

  • โœ๏ธ Write a function to check if a number is prime
  • ๐Ÿงฎ Write a function to calculate the factorial of a number
  • ๐Ÿ“„ Create a function that reads a file and returns line count
  • ๐Ÿ“Š Write a function that returns summary statistics from a list
  • ๐Ÿ” Write a login validation function with username/password check

๐Ÿงฉ Types of Functions in Python

Function Type Description Real-Time Use Case Example
1. Built-in Functions Predefined functions in Python print(), len(), type(), range()
2. User-defined Functions Functions created by users using def keyword def calculate_salary():, def send_email():
3. Lambda Functions Anonymous functions using lambda keyword (single-expression) Sorting a list of tuples, filtering data with conditions
4. Recursive Functions A function that calls itself to solve smaller sub-problems Calculating factorial, Fibonacci series
5. Generator Functions Use yield to return one item at a time without storing the entire sequence Reading large files line-by-line, paginated API requests
6. Higher-Order Functions Functions that take other functions as arguments or return functions map(), filter(), reduce()
7. Nested Functions Functions defined inside other functions (inner functions) Scope management, closures, decorators
8. Decorator Functions Functions that modify the behavior of another function Logging, authorization, timing a function’s execution
9. Callback Functions Function passed as argument and called later Used in UI event handling, asynchronous programming
10. Partial Functions Pre-filling arguments using functools.partial Pre-define behavior like setting currency in conversion APIs
11. Coroutine Functions Declared with async def, used with await to handle asynchronous calls Async I/O operations, web scraping, concurrent API calls
12. Static Methods Defined in classes using @staticmethod, doesn't use class instance Utility methods inside class that don’t need access to class data
13. Class Methods Use @classmethod, receives cls as argument instead of self Factory methods to create class instances from different inputs

๐Ÿง  All Python Function Types - Explained with Examples

1๏ธโƒฃ Built-in Functions ๐Ÿ“ฆ

These are pre-defined functions provided by Python.

print("Hello World!")
len([1, 2, 3])

Use Case: Logging, counting, formatting, etc.

2๏ธโƒฃ User-defined Functions ๐Ÿง‘‍๐Ÿ’ป

Created using def keyword.

def greet(name):
    print(f"Hello {name}")

Use Case: Custom logic in apps

3๏ธโƒฃ Lambda Functions โšก

Anonymous functions with lambda.

square = lambda x: x ** 2
print(square(5))

Use Case: Sorting, filtering

4๏ธโƒฃ Recursive Functions ๐Ÿ”

Function calling itself repeatedly.

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

Use Case: Tree traversal, factorial

5๏ธโƒฃ Generator Functions ๐Ÿงต

Use yield to return items one by one.

def count_up():
    yield 1
    yield 2

Use Case: Large file reading, streams

6๏ธโƒฃ Higher-Order Functions ๐Ÿง 

Accepts/returns other functions.

def apply_twice(func, val):
    return func(func(val))

print(apply_twice(lambda x: x + 1, 3))

Use Case: Functional programming

7๏ธโƒฃ Nested Functions ๐Ÿ”„

Functions defined inside other functions.

def outer():
    def inner():
        print("Inner")
    inner()

Use Case: Closures, scope control

8๏ธโƒฃ Decorator Functions ๐ŸŽฏ

Wrap another function to modify its behavior.

def logger(func):
    def wrapper():
        print("Logging...")
        return func()
    return wrapper

@logger
def hello():
    print("Hello World!")

Use Case: Authentication, timing

9๏ธโƒฃ Callback Functions ๐Ÿ“ž

Passed as argument to be called later.

def process(callback):
    print("Start")
    callback()
    print("End")

process(lambda: print("Running..."))

Use Case: Event handling, async logic

๐Ÿ”Ÿ Partial Functions ๐Ÿ”’

Pre-fill function arguments using functools.partial

from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)

Use Case: Currency conversion, API configuration

1๏ธโƒฃ1๏ธโƒฃ Coroutine Functions โš™๏ธ

Declared with async def and uses await

import asyncio

async def hello():
    await asyncio.sleep(1)
    print("Async Hello")

Use Case: Web scraping, I/O tasks

1๏ธโƒฃ2๏ธโƒฃ Static Method ๐Ÿ“š

Doesn't need class instance. Defined using @staticmethod.

class Math:
    @staticmethod
    def add(a, b):
        return a + b

Use Case: Utility methods inside classes

1๏ธโƒฃ3๏ธโƒฃ Class Method ๐Ÿงฐ

Uses @classmethod and gets `cls` as argument.

class Person:
    def __init__(self, name):
        self.name = name

    @classmethod
    def create_anonymous(cls):
        return cls("Anonymous")

Use Case: Alternative constructors

โœ… Python Function Types - Summary with Emojis

๐Ÿ“ฆBuilt-in→ Already available
๐Ÿง‘‍๐Ÿ’ปUser-defined→ Your own logic
โšกLambda→ One-liners
๐Ÿ”Recursive→ Self-calling
๐ŸงตGenerator→ Stream data
๐Ÿง Higher-Order→ Functions as tools
๐ŸงญNested→ Scoped inside
๐ŸŽฏDecorator→ Add new behaviors
๐Ÿ“žCallback→ Event-based
๐Ÿ”’Partial→ Lock in defaults
โš™๏ธCoroutine→ Async programming
๐Ÿ“šStatic Method→ Class helper (no state)
๐ŸงฐClass Method→ Acts on class-level data