Lesson · 40 min · Free
Python Data Types
Python 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 { font-family: m
Python Data Types
Welcome to this lesson on Python Data Types, a fundamental concept essential for any programming endeavor, especially in data-intensive fields like pharmacy and biotechnology. Understanding data types is crucial because they dictate what kind of values a variable can hold, what operations can be performed on those values, and how data is stored in memory. In scientific computing, we constantly deal with numbers, text, and complex data structures, making a solid grasp of Python's data types indispensable. Python is a dynamically typed language, meaning you don't explicitly declare the data type of a variable when you create it. Python infers the type based on the value assigned. While this offers flexibility, it's vital for you, the programmer, to be aware of the underlying types to avoid common errors and write efficient code. We'll explore the most common built-in data types relevant to your domain.
Core Python Data Types for Scientific Applications
1. Numeric Types: int, float, complex
These are perhaps the most frequently used data types in scientific and quantitative analyses. Python offers three distinct numeric types: Integers ( int ): Whole numbers, positive or negative, without a decimal point. Examples include patient IDs, counts of cells, or drug dosage units. Python integers have arbitrary precision, meaning they can be as large as your system's memory allows, which is incredibly useful for computations involving very large numbers without overflow issues. Floating-Point Numbers ( float ): Numbers with a decimal point, representing real numbers. This is your go-to for measurements, concentrations, p-values, or any data requiring precision beyond whole numbers. Python floats are typically implemented using a double-precision floating-point representation (64-bit), offering significant precision. Complex Numbers ( complex ): Numbers with a real and an imaginary part, written as a + bj . While less common in everyday pharmaceutical data analysis, complex numbers are fundamental in fields like signal processing, quantum mechanics, and certain types of electrical engineering, which might intersect with advanced biophysics or imaging techniques. # Numeric Type Examples patient_id = 12345 print(f"Type of patient_id: {type(patient_id)}") # Output: <class 'int'> drug_concentration = 0.523 # mg/mL print(f"Type of drug_concentration: {type(drug_concentration)}") # Output: <class 'float'> frequency_component = 3 + 2.5j print(f"Type of frequency_component: {type(frequency_component)}") # Output: <class 'complex'> # Operations on numeric types total_dose = 2 * drug_concentration # Multiplies float by int, result is float print(f"Total dose: {total_dose}, Type: {type(total_dose)}") # Output: Total dose: 1.046, Type: <class 'float'>
2. Boolean Type: bool
The Boolean type represents logical values: True or False . These are essential for control flow ( if/else statements), filtering data, and representing binary states. For example, a patient either has a condition (True) or does not (False), or a drug trial either met its primary endpoint (True) or did not (False). # Boolean Type Examples is_positive_for_marker = True print(f"Type of is_positive_for_marker: {type(is_positive_for_marker)}") # Output: <class 'bool'> has_side_effect = False print(f"Type of has_side_effect: {type(has_side_effect)}") # Output: <class 'bool'> # Booleans in conditional logic if is_positive_for_marker: print("Patient requires further investigation.") else: print("Patient does not require further investigation based on this marker.")
3. Sequence Types: str, list, tuple
Sequence types are ordered collections of items. They allow you to store multiple values and access them by their position (index). Strings ( str ): Sequences of characters. Used for textual data like patient names, drug names, gene sequences, or experimental notes. Strings are immutable, meaning once created, their content cannot be changed. Lists ( list ): Ordered, mutable sequences of items. Lists are highly versatile and can hold items of different data types. You'll use lists extensively for storing collections of data that might change, such as a list of experimental readings, a series of patient responses, or a collection of genes. Tuples ( tuple ): Ordered, immutable sequences of items. Like lists, tuples can hold heterogeneous data. The key difference is immutability; once a tuple is created, its elements cannot be changed, added, or removed. Tuples are often used for data that shouldn't change, like coordinates, database records, or function arguments that are meant to be constant.
4. Mapping Type: dict
Dictionaries ( dict ): Unordered collections of key-value pairs. Dictionaries are incredibly powerful for storing and retrieving data based on a unique key, rather than an index. Think of them as a lookup table. For instance, you could store patient records where the key is the patient ID and the value is a dictionary containing their name, age, and medical history. Or, mapping drug names to their chemical formulas.
5. Set Types: set, frozenset
Sets ( set ): Unordered collections of unique items. Sets are useful when you need to store a collection of items where duplicates are not allowed, and the order doesn't matter. They are highly optimized for operations like checking for membership, finding unions, intersections, and differences between collections (e.g., comparing lists of genes present in two different samples). frozenset is an immutable version of a set.
Key Takeaways
Python is dynamically typed, inferring data types from assigned values. int and float are crucial for numerical data in scientific computing. bool values (True/False) are fundamental for logic and control flow. str handles all textual data, from names to gene sequences. list provides mutable, ordered collections for dynamic data. tuple offers immutable, ordered collections for fixed data. dict enables efficient key-value lookups, perfect for structured records. set stores unique, unordered items, useful for membership testing and set operations.
Practice Exercise: Identifying and Using Data Types
Imagine you are collecting data for a new drug trial. You need to store the following information for a single patient: Patient ID: PNT001 Age: 62 Weight (kg): 78.5 Gender: 'Female' Known Allergies: ['Penicillin', 'Sulfonamides'] Drug Dosage (mg): 250 Time of Administration (HH:MM): '09:30' Is the patient responding positively to the drug? False Your task is to: Create Python variables for each piece of information, assigning the appropriate data type. Print each variable and its corresponding data type using the type() function. Write a single line of code that calculates the patient's BMI (Body Mass Index) if their height is 1.70 meters (BMI = weight / (height * height)). Store this in a new variable and print its value and type. This exercise will solidify your understanding of how to apply different Python data types to real-world biological and medical data.
Watch the full lesson — free
This topic is part of The Complete Python Bootcamp: Basics to Pharma & Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →