5. Variables, Data Types, Casting & Operators
Variables, primitive data types, type casting, mathematical operators, and posology calculations in Python.
Variables & Dynamic Typing in Python
Think of a Variable in Python like a labeled container or prescription tag in a pharmacy. The tag gives a name (e.g. tablet_count), and inside is the value stored in memory (e.g. 100).
Key Features of Variables
- Dynamic Typing: You don't need to specify whether a variable is a number or text in advance. Python detects the data type automatically from the assigned value.
- Reassignable: A variable can hold a number initially (
stock = 100) and later be updated to text (stock = "Out of Stock"). - Multiple Assignment: You can set multiple variables at once:
drug, dose, unit = "Paracetamol", 500, "mg". - Memory Address: Every variable points to a location in memory. You can check this unique memory ID using
id(var).
PEP-8 Identifier Naming Rules
| Rule | Valid Examples (✔) | Invalid Examples (❌) & Reason |
|---|---|---|
| Starting Character | dose, _patient_id, Age | 1st_dose (Cannot begin with a number) |
| Allowed Characters | tablet_weight_mg, batch2026 | dose-mg, price$ (No hyphens or special symbols) |
| Case-Sensitivity | dose, Dose, DOSE (3 separate variables) | Mixing upper and lower case causes a NameError |
| Reserved Keywords | patient_class, is_pass | def, class, if, import (Reserved Python words) |
Primitive Data Types in Python
A Data Type tells Python what kind of value a variable holds and what operations can be performed on it. Python provides 4 core basic types:
| Data Type | Python Class | Description | Pharmacy Examples |
|---|---|---|---|
| Integer | int | Whole numbers without any decimal point (positive, negative, or zero). | tablets = 30, patient_age = 8 |
| Float | float | Numbers with decimal points or scientific notation. | plasma_ph = 7.41, elimination_rate = 0.045 |
| String | str | Text characters enclosed in single ('...') or double ("...") quotes. | drug = "Ciprofloxacin" |
| Boolean | bool | Logical values representing only True or False. | is_sterile = True, is_expired = False |
Checking Data Types
Use type() to inspect the data type, and isinstance(variable, type) to check if a variable matches an expected type:
Type Casting (Type Conversion)
Type Casting means converting a value from one data type into another. This is especially important in pharmacy programs because all data entered by users via keyboard starts as text (str) and must be converted to numbers before performing calculations.
1. Automatic Conversion (Implicit Casting)
Python automatically promotes narrower types to wider types without precision loss (e.g. 500 + 0.5 = 500.5).
2. Manual Conversion (Explicit Casting)
Programmer manually converts types using: int(), float(), str(), bool().
Basic Operators in Python
1. Arithmetic Operators (Math Calculations)
| Operator | Meaning | Example | Result | Pharmacy Scenario |
|---|---|---|---|---|
| + | Addition | 250 + 250 | 500 | Combining ingredients |
| - | Subtraction | 100 - 15.5 | 84.5 | Loss on Drying (LOD) analysis |
| * | Multiplication | 15 * 3 | 45 | Total tablets for a 15-day course |
| / | Float Division | 500 / 2 | 250.0 | Dividing a daily dose into two halves |
| // | Floor Division | 100 // 14 | 7 | How many complete 14-tablet blister strips can be made from 100 tablets |
| % | Modulus (Remainder) | 100 % 14 | 2 | Remaining loose tablets left over after packaging full strips |
| ** | Exponent (Power) | 2 ** 4 | 16 | Pharmacokinetic decay formulas (2^4) |
2. Comparison & Logical Operators
- Comparison (
==, !=, >, <, >=, <=): Compares two values and produces aTrueorFalseresult. - Logical
and: True only if both conditions are met (conc >= 10.0 and conc <= 20.0checks if the drug is inside the therapeutic window). - Logical
or: True if at least one condition is met (temp < 2.0 or temp > 8.0triggers a cold-chain storage alarm). - Logical
not: Inverts the result (not is_expired).
Input & Output Operations (print, input, f-strings)
Programs interact with users by taking input through the keyboard with input() and displaying results with print() and modern f-strings:
| Formatting Task | f-string Syntax | Example Output |
|---|---|---|
| 2 Decimal Places (Dosage / mg) | f"{dose:.2f} mg" | 166.67 mg |
| Scientific / PK Notation | f"{ke:.3e}" | 4.500e-02 |
| Percentage Display | f"{purity:.1%}" | 99.4% |
| Column Width Alignment | f"{drug:<15} {dose:>8.1f} mg" | Paracetamol 500.0 mg |
Basic String Operations & Manipulation Techniques
A String (str) is an ordered sequence of text characters enclosed in quotes. In pharmaceutical programming, strings handle patient records, drug names, batch codes, and raw CSV files.
1. String Indexing & Slicing
| Operation | Syntax | Example (drug = "Paracetamol") | Result |
|---|---|---|---|
| First Letter | string[0] | drug[0] | 'P' |
| Last Letter | string[-1] | drug[-1] | 'l' |
| Substring Slice | string[0:4] | drug[0:4] | 'Para' |
| Reverse String | string[::-1] | drug[::-1] | 'lometacaraP' |
2. Essential String Methods for Pharmacy Data
| Method | Description | Example | Cleaned Output |
|---|---|---|---|
| .strip() | Removes leading and trailing spaces | " Paracetamol ".strip() | "Paracetamol" |
| .upper() / .lower() | Converts text to uppercase or lowercase | "amoxicillin".upper() | "AMOXICILLIN" |
| .replace() | Replaces substring or outdated batch code | "LOT-2024".replace("2024", "2026") | "LOT-2026" |
| .split(",") | Splits raw text line into a list by comma | "Aspirin,100mg".split(",") | ['Aspirin', '100mg'] |
Standard & Third-Party Libraries (Installing with pip)
A Module or Library is a collection of pre-written functions that you can import into your code, saving you from writing mathematical or statistical tools from scratch.
1. Built-in Standard Libraries
| Module | Key Functions | Pharmacy Use Case |
|---|---|---|
| math | math.sqrt(), math.exp(), math.log() | Elimination half-life and decay equations |
| statistics | statistics.mean(), statistics.stdev() | Tablet weight variation and assay limits |
| datetime | datetime.date(), datetime.timedelta() | Shelf-life calculation and medicine expiry dates |
2. Package Management with pip
| Task | Terminal Command | Description |
|---|---|---|
| Install Package | pip install pandas matplotlib | Installs Pandas and Matplotlib from PyPI |
| Upgrade Package | pip install --upgrade pandas | Updates package to newest release |
| List Installed | pip list | Shows all installed libraries |
| Uninstall Package | pip uninstall pandas -y | Removes the specified library |
Solved Practical: Young's Pediatric Dosage Rule
Young's Formula: Child Dose = (Age / (Age + 12)) * Adult Dose
# B.Pharm BP101T Practical Lab: Young's Rule Solver
def calculate_pediatric_dose():
print("--- Young's Rule Pediatric Dosage Calculator ---")
# Taking inputs from user
drug_name = input("Enter Drug Name (e.g. Paracetamol): ")
adult_dose = float(input("Enter Adult Dose in mg: "))
child_age = int(input("Enter Child Age in Years (1-12): "))
# Young's Rule Formula
child_dose = (child_age / (child_age + 12)) * adult_dose
# Displaying Result
print(f"\nDrug Prescribed: {drug_name}")
print(f"Adult Dose : {adult_dose} mg")
print(f"Child Dose : {child_dose:.2f} mg")
if __name__ == "__main__":
calculate_pediatric_dose()