- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Basics To Advanced Level / of Python Function Design
๐ง 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