PCI BP101T • Unit 1 (Module 5 of 5)⏱ 15 Min ReadEnglish + हिन्दी

5. Variables, Data Types, Casting & Operators

Variables, primitive data types, type casting, mathematical operators, and posology calculations in Python.

01

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

RuleValid Examples (✔)Invalid Examples (❌) & Reason
Starting Characterdose, _patient_id, Age1st_dose (Cannot begin with a number)
Allowed Characterstablet_weight_mg, batch2026dose-mg, price$ (No hyphens or special symbols)
Case-Sensitivitydose, Dose, DOSE (3 separate variables)Mixing upper and lower case causes a NameError
Reserved Keywordspatient_class, is_passdef, class, if, import (Reserved Python words)
# Storing different values in variables
drug_name = "Amoxicillin" # String (text)
strength_mg = 500 # Integer (whole number)
half_life_hr = 1.2 # Float (decimal number)
is_approved = True # Boolean (True/False)
morning_dose, evening_dose = 250.0, 250.0 # Multiple
02

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 TypePython ClassDescriptionPharmacy Examples
IntegerintWhole numbers without any decimal point (positive, negative, or zero).tablets = 30, patient_age = 8
FloatfloatNumbers with decimal points or scientific notation.plasma_ph = 7.41, elimination_rate = 0.045
StringstrText characters enclosed in single ('...') or double ("...") quotes.drug = "Ciprofloxacin"
BooleanboolLogical 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:

dose = 250
ph = 6.8
print(type(dose)) # <class 'int'>
print(isinstance(ph, float)) # True
03

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().

# Explicit Type Casting in Dosage Computation
raw_dose = "125.5" # str
dose = float(raw_dose) # 125.5 (float)
full_strips = int(3.95) # 3 (Cuts off decimal without rounding)
04

Basic Operators in Python

1. Arithmetic Operators (Math Calculations)

OperatorMeaningExampleResultPharmacy Scenario
+Addition250 + 250500Combining ingredients
-Subtraction100 - 15.584.5Loss on Drying (LOD) analysis
*Multiplication15 * 345Total tablets for a 15-day course
/Float Division500 / 2250.0Dividing a daily dose into two halves
//Floor Division100 // 147How many complete 14-tablet blister strips can be made from 100 tablets
%Modulus (Remainder)100 % 142Remaining loose tablets left over after packaging full strips
**Exponent (Power)2 ** 416Pharmacokinetic decay formulas (2^4)

2. Comparison & Logical Operators

  • Comparison (==, !=, >, <, >=, <=): Compares two values and produces a True or False result.
  • Logical and: True only if both conditions are met (conc >= 10.0 and conc <= 20.0 checks if the drug is inside the therapeutic window).
  • Logical or: True if at least one condition is met (temp < 2.0 or temp > 8.0 triggers a cold-chain storage alarm).
  • Logical not: Inverts the result (not is_expired).
05

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 Taskf-string SyntaxExample Output
2 Decimal Places (Dosage / mg)f"{dose:.2f} mg"166.67 mg
Scientific / PK Notationf"{ke:.3e}"4.500e-02
Percentage Displayf"{purity:.1%}"99.4%
Column Width Alignmentf"{drug:<15} {dose:>8.1f} mg"Paracetamol 500.0 mg
06

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

OperationSyntaxExample (drug = "Paracetamol")Result
First Letterstring[0]drug[0]'P'
Last Letterstring[-1]drug[-1]'l'
Substring Slicestring[0:4]drug[0:4]'Para'
Reverse Stringstring[::-1]drug[::-1]'lometacaraP'

2. Essential String Methods for Pharmacy Data

MethodDescriptionExampleCleaned 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']
# Cleaning and Parsing Hospital Prescription Data
raw_drug = " amoxicillin 500mg "
clean_drug = raw_drug.strip().title() # 'Amoxicillin 500Mg'
name, strength = "Paracetamol,500mg".split(",")
07

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

ModuleKey FunctionsPharmacy Use Case
mathmath.sqrt(), math.exp(), math.log()Elimination half-life and decay equations
statisticsstatistics.mean(), statistics.stdev()Tablet weight variation and assay limits
datetimedatetime.date(), datetime.timedelta()Shelf-life calculation and medicine expiry dates

2. Package Management with pip

TaskTerminal CommandDescription
Install Packagepip install pandas matplotlibInstalls Pandas and Matplotlib from PyPI
Upgrade Packagepip install --upgrade pandasUpdates package to newest release
List Installedpip listShows all installed libraries
Uninstall Packagepip uninstall pandas -yRemoves the specified library
LAB

Solved Practical: Young's Pediatric Dosage Rule

Young's Formula: Child Dose = (Age / (Age + 12)) * Adult Dose

youngs_dosage_solver.py
# 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()
Back: 4. Advantages of IDEs✓ Completed Unit 1 • Return to Python Course Hub