Lesson · 40 min · Free
Python Variables & Data Types
Python Variables & Data Types body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; } code { fo
Python Variables & Data Types
Welcome to the foundational module on Python Variables and Data Types. In the realm of data science, particularly within pharmacy and biotechnology, understanding how Python stores and manipulates information is paramount. Whether you're analyzing clinical trial data, simulating molecular interactions, or managing drug inventory, the underlying principles of variables and data types dictate the efficiency and accuracy of your code. This module will equip you with the essential knowledge to effectively handle data in Python. At its core, a variable in Python is a named storage location that holds a value. Think of it as a labeled box where you can put different kinds of information. The beauty of Python is its dynamic typing; you don't need to explicitly declare the type of data a variable will hold. Python infers the type at runtime. This flexibility is a powerful feature for rapid prototyping and iterative data analysis common in biotech research. The data type defines the kind of value a variable can store and the operations that can be performed on it. For instance, you can perform arithmetic operations on numbers but not directly on text. Python offers several built-in data types, each suited for different purposes. For data scientists, particularly those working with biological and chemical datasets, the most frequently encountered types include numeric types (integers, floats), boolean, strings, and collections (lists, tuples, dictionaries, sets).
Common Data Types in Scientific Computing
Let's delve into the most frequently used data types that you will encounter and utilize in pharmacy and biotechnology applications: Numeric Types: int (Integers): Whole numbers, positive or negative, without a decimal point. E.g., patient IDs, number of molecules, dosage counts. float (Floating-point numbers): Real numbers that can have a fractional part. E.g., drug concentrations, p-values, molecular weights. str (Strings): Sequences of characters used to represent text. E.g., gene names, patient demographics, clinical notes, chemical compound names. Strings are immutable, meaning once created, their content cannot be changed. bool (Booleans): Represent truth values, either True or False . Essential for conditional logic, such as checking if a patient responded to treatment or if a compound passed a solubility test. Collection Types: These allow you to store multiple items in a single variable. list : Ordered, mutable collections of items. Items can be of different types. Ideal for storing sequences of experimental results, patient cohorts, or a series of drug candidates. tuple : Ordered, immutable collections of items. Similar to lists but cannot be changed after creation. Useful for fixed sets of data, like coordinates (x, y, z) or specific assay parameters. dict (Dictionary): Unordered collections of key-value pairs. Each key must be unique. Perfect for storing structured data like patient records (key=patient_id, value=patient_info), or experimental metadata (key=assay_type, value=parameters). set : Unordered collections of unique items. Useful for membership testing and eliminating duplicate entries, e.g., finding unique gene identifiers in a dataset. Understanding the distinctions between these types is crucial for writing efficient and error-free code. For instance, attempting to perform arithmetic on a string will result in a runtime error, while using a list when a tuple is more appropriate might lead to unintended modifications of critical data. Let's look at some practical examples of declaring variables and assigning different data types: # Example 1: Basic Variable Assignment and Type Checking # Integer for patient count patient_count = 150 print(f"Patient Count: {patient_count}, Type: {type(patient_count)}") # Float for drug concentration (e.g., mg/mL) drug_concentration = 0.75 print(f"Drug Concentration: {drug_concentration}, Type: {type(drug_concentration)}") # String for a gene name gene_name = "BRCA1" print(f"Gene Name: {gene_name}, Type: {type(gene_name)}") # Boolean for a clinical trial status is_trial_active = True print(f"Is Trial Active: {is_trial_active}, Type: {type(is_trial_active)}") # List of patient IDs patient_ids = [101, 102, 103, 104] print(f"Patient IDs: {patient_ids}, Type: {type(patient_ids)}") # Tuple for molecular coordinates (x, y, z) molecular_coordinates = (12.3, 5.8, 9.1) print(f"Molecular Coordinates: {molecular_coordinates}, Type: {type(molecular_coordinates)}") # Dictionary for a patient's medical record patient_record = { "ID": 205, "Age": 62, "Diagnosis": "Hypertension", "Medications": ["Lisinopril", "Aspirin"] } print(f"Patient Record: {patient_record}, Type: {type(patient_record)}") # Set of unique drug targets drug_targets = {"GPCR", "Kinase", "Ion Channel", "GPCR"} # Note: GPCR appears twice but will only be stored once print(f"Drug Targets: {drug_targets}, Type: {type(drug_targets)}") Python also allows for dynamic re-assignment of variables. A variable can hold an integer, and later be reassigned to hold a string. While this offers flexibility, it's generally good practice to maintain consistent data types for variables within a specific logical block to avoid confusion and potential errors. # Example 2: Dynamic Re-assignment and Type Conversion # Initial assignment as an integer data_point = 45 print(f"Initial data_point: {data_point}, Type: {type(data_point)}") # Re-assign to a float data_point = 45.0 print(f"Re-assigned data_point: {data_point}, Type: {type(data_point)}") # Re-assign to a string data_point = "Measurement A" print(f"Re-assigned data_point: {data_point}, Type: {type(data_point)}") # Type conversion (casting) # Converting a string representing a number to an integer or float dosage_str = "250" dosage_int = int(dosage_str) print(f"Dosage as int: {dosage_int}, Type: {type(dosage_int)}") concentration_str = "1.25" concentration_float = float(concentration_str) print(f"Concentration as float: {concentration_float}, Type: {type(concentration_float)}") # Attempting to convert inappropriate types will raise an error # Uncomment the line below to see the error: # invalid_conversion = int("hello") # print(invalid_conversion) Type conversion, or casting, is a critical technique. You'll frequently encounter scenarios where data imported from external sources (like CSV files or databases) might be read as strings, even if they represent numbers. Explicitly converting them using functions like int() , float() , or str() is essential before performing numerical operations or string manipulations.
Key Takeaways
Variables are named containers for storing data in Python. Python is dynamically typed, meaning variable types are inferred at runtime. Common data types in data science include int , float , str , bool , list , tuple , dict , and set . Each data type supports specific operations and has unique characteristics (e.g., mutability, order). Understanding data types is fundamental for efficient data manipulation and avoiding runtime errors in scientific computing. Type conversion (casting) allows you to change the data type of a variable, which is often necessary when processing external data.
Practice Exercise: Clinical Data Representation
Imagine you are tasked with representing a small dataset for a clinical trial patient in Python. Create variables for the following information, choosing the most appropriate data type for each, and then print each variable along with its inferred type using an f-string and the type() function: Patient ID: 45678 Patient Age: 58 Drug Administered: "CompoundX" Dosage (in mg): 150.5 Adverse Event Reported (Yes/No): True List of Symptoms (e.g., "Headache" , "Nausea" ): ["Headache", "Nausea", "Fatigue"] Drug Interaction Status (a dictionary with drug names as keys and boolean indicating interaction as values): {"DrugA": False, "DrugB": True} After defining these variables, demonstrate a type conversion: take the patient ID (which is an integer) and convert it to a string. Print the new string variable and its type.
Watch the full lesson — free
This topic is part of Python for Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →