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 :
.
def greet(name):
print(f"Hello, {name} ๐!")
greet("Sairam")
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 |
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 |
These are pre-defined functions provided by Python.
print("Hello World!")
len([1, 2, 3])
Use Case: Logging, counting, formatting, etc.
Created using def
keyword.
def greet(name):
print(f"Hello {name}")
Use Case: Custom logic in apps
Anonymous functions with lambda
.
square = lambda x: x ** 2
print(square(5))
Use Case: Sorting, filtering
Function calling itself repeatedly.
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
Use Case: Tree traversal, factorial
Use yield
to return items one by one.
def count_up():
yield 1
yield 2
Use Case: Large file reading, streams
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
Functions defined inside other functions.
def outer():
def inner():
print("Inner")
inner()
Use Case: Closures, scope control
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
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
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
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
Doesn't need class instance. Defined using @staticmethod
.
class Math:
@staticmethod
def add(a, b):
return a + b
Use Case: Utility methods inside classes
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