BP101T Unit 4 – Functions, Modules & Pharma Algorithms
Unit 4 teaches modular programming principles in Python, user-defined functions with parameter passing, default and keyword arguments, local vs global scope, organizing reusable pharmaceutical modules (.py packages), and defensive exception handling (try-except-finally) for dispensary and laboratory software.
📋 Prescribed Syllabus Topics
📖 Detailed Lecture Notes & Solved Examples
11. Function Architecture, Parameter Passing & Scope in Lab Scripts
Dedicated Webpage➔A function is an encapsulated, reusable block of organized instructions that takes input arguments, performs a specific computational task, and returns an output. Functions follow the DRY (Don't Repeat Yourself) principle. In pharmaceutical laboratory systems, functions prevent error-prone code duplication across dilution, posology, and assay calculations. Variables created inside a function exist only within its local scope and cannot accidentally overwrite global variables.Function ek aisa reusable block hota hai jisme hum arguments dete hain aur wo calculation karke result `return` karta hai. Iska sabse bada fayda ye hai ki code bar-bar likhna nahi padta (DRY principle). Function ke andar ke variables bahar access nahi hote (Local scope).
▶Comprehensive Stock Solution Dilution Calculator Function
Implementing $C_1V_1 = C_2V_2$ with positional, keyword, and default parameters.
def calculate_dilution_volume(target_conc, target_vol, stock_conc=100.0):
"""
Calculates required stock volume using C1 * V1 = C2 * V2.
Parameters:
target_conc (float): Desired final concentration (% w/v or mg/mL)
target_vol (float): Desired final volume (mL)
stock_conc (float): Available stock concentration (default = 100.0% pure)
Returns:
float: Volume of stock solution required in mL
"""
if stock_conc <= target_conc:
raise ValueError("Stock concentration must be strictly greater than target concentration.")
# V1 = (C2 * V2) / C1
stock_vol_required = (target_conc * target_vol) / stock_conc
water_to_add = target_vol - stock_vol_required
return stock_vol_required, water_to_add
# Call using positional and keyword arguments
v_stock, v_water = calculate_dilution_volume(target_conc=2.5, target_vol=500.0, stock_conc=20.0)
print(f"Measure {v_stock:.2f} mL of stock and add {v_water:.2f} mL of purified water.")
- •`def` keyword declares a function; `return` sends values back to caller.
- •Docstrings (`"""..."""`) document function purpose, parameters, and return types.
- •Default arguments (`stock_conc=100.0`) provide fallback values if omitted by user.
- •Local variables: Defined inside function body, destroyed when function finishes execution.
22. Creating Custom Pharmacy Python Modules (.py Packages)
Dedicated Webpage➔A Python module is simply a file containing Python definitions and statements ending with the `.py` extension. Grouping related mathematical formulas into modular files (e.g., `posology.py`, `pharmacokinetics.py`) allows clean imports into any project using `import posology` or `from posology import youngs_rule`.Custom module ka matlab hai apne formulas ko ek `.py` file me save karna. Jaise `pharmatools.py` bana kar hum kisi bhi dusre script me `import pharmatools` karke uske formulas direct call kar sakte hain.
▶Structuring a Custom Pharmaceutical Toolkit Module
Demonstrating how a standalone file `pharmatools.py` is written and imported.
# File: pharmatools.py
def half_life(ke):
"""Returns elimination half-life from Ke"""
return 0.693 / ke
def body_surface_area(weight_kg, height_cm):
"""Mosteller BSA Formula: sqrt((Height_cm * Weight_kg) / 3600)"""
import math
return math.sqrt((height_cm * weight_kg) / 3600.0)
# In another main script:
# import pharmatools
# bsa = pharmatools.body_surface_area(weight_kg=70, height_cm=175)
# print(f"Patient BSA: {bsa:.2f} m^2")
- •`import module_name`: Imports entire module into namespace.
- •`from module_name import specific_func`: Imports selected functions directly.
- •`if __name__ == '__main__':`: Prevents test code from running when the file is imported elsewhere.
33. Defensive Exception Handling (try-except-else-finally) for Lab Software
Dedicated Webpage➔In clinical dispensaries and hospital software, an unhandled runtime error (like typing text in a dose box or dividing by zero) could cause system crashes. Python's structured exception handling catches runtime errors gracefully, presents user-friendly error guidance, and ensures critical resources (like open database files) are safely closed.Hospital ya pharmacy software me agar koi zero se divide kar de ya galat text daal de, toh software crash hone ke bajaye `try-except` block us galti ko pakad leta hai aur warning deta hai. `finally` block hamesha run hota hai taaki file/database safely close ho jaye.
▶Robust Dispensary Dose Entry Validator
Using try-except-else-finally blocks to defensively handle faulty user inputs.
def safe_dose_entry():
try:
user_weight = float(input("Enter patient weight (kg): "))
if user_weight <= 0:
raise ValueError("Weight must be a positive number greater than 0.")
target_mg_per_kg = float(input("Enter mg/kg prescribed: "))
calculated_dose = user_weight * target_mg_per_kg
except ValueError as ve:
print(f"Validation Error: Invalid input value! Details: {ve}")
except ZeroDivisionError:
print("Arithmetic Error: Division by zero encountered.")
else:
# Executes ONLY if no exceptions were raised
print(f"Validated Dose: {calculated_dose:.2f} mg safely calculated.")
finally:
# Executes UNCONDITIONALLY (ideal for logging/cleanup)
print("Dispensary validation audit log completed.")
- •`try`: Contains code that could trigger runtime errors.
- •`except SpecificError`: Catches and handles known exceptions.
- •`else`: Executes only if the try block ran without exceptions.
- •`finally`: Executes unconditionally, regardless of whether an error occurred or was handled.
- •`raise ValueError(...)`: Manually throws custom exceptions when business rules are violated.
- Distinguish between compile/syntax errors (detected before run) and exceptions (runtime failures).
- Explain the exact purpose of the `finally` block in pharmaceutical database transactions.