Lesson · 40 min · Free
Python For Loops: Basics & Application
Python For Loops: Basics & Application 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; }
Python For Loops: Basics & Application
Welcome to this lesson on Python for loops, a fundamental control flow structure essential for automating repetitive tasks and processing data efficiently. In pharmaceutical research, you'll frequently encounter scenarios requiring iteration, such as processing patient data, analyzing experimental results from multiple samples, or simulating drug interactions over time. Understanding for loops will empower you to write more concise, powerful, and scalable Python scripts for these applications. At its core, a for loop is used for iterating over a sequence (that is, a list, tuple, dictionary, set, or string) or other iterable objects. It allows you to execute a block of code once for each item in the sequence. This eliminates the need to write the same code multiple times for each item, significantly reducing redundancy and potential for errors.
Understanding the Syntax and Iteration
The basic syntax of a for loop in Python is straightforward: for item in iterable: # code to be executed for each item # indented block Here, item is a temporary variable that takes on the value of the next element in the iterable during each pass of the loop. The iterable is the collection of items you want to go through. The indented block of code below the for statement is executed for every item .
Example 1: Iterating Through a List of Compounds
Imagine you have a list of experimental compounds and you want to print each one. A for loop makes this simple: compounds = ["Aspirin", "Paracetamol", "Ibuprofen", "Omeprazole"] print("Analyzing compounds:") for compound in compounds: print(f"- {compound}") # Expected output: # Analyzing compounds: # - Aspirin # - Paracetamol # - Ibuprofen # - Omeprazole In this example, compound is the iteration variable. In the first iteration, compound is "Aspirin", then "Paracetamol", and so on, until all elements in the compounds list have been processed.
Example 2: Processing Patient Data (Numerical Iteration with range())
Often, you might need to perform an action a specific number of times, or iterate through indices. The built-in range() function is incredibly useful for this. range(n) generates a sequence of numbers from 0 up to (but not including) n. You can also specify a start and step (e.g., range(start, stop, step) ). Let's say you have 5 patient samples and you want to simulate processing each one: num_patients = 5 blood_pressure_readings = [120, 135, 118, 140, 125] # Sample data print("Processing patient data:") for i in range(num_patients): print(f"Patient {i+1}: Blood Pressure = {blood_pressure_readings[i]} mmHg") # Expected output: # Processing patient data: # Patient 1: Blood Pressure = 120 mmHg # Patient 2: Blood Pressure = 135 mmHg # Patient 3: Blood Pressure = 118 mmHg # Patient 4: Blood Pressure = 140 mmHg # Patient 5: Blood Pressure = 125 mmHg Here, range(num_patients) generates numbers 0, 1, 2, 3, 4. We use i+1 to display patient numbers starting from 1, and blood_pressure_readings[i] to access the corresponding reading from our list using the index i . for loops are not limited to lists; they work with strings (iterating character by character), tuples, dictionaries (iterating over keys by default, or items/values explicitly), and other iterable objects. This versatility makes them an indispensable tool in your Python toolkit for pharmaceutical research.
Key Takeaways:
for loops iterate over sequences (lists, tuples, strings, etc.) and other iterable objects. The syntax is for item in iterable: followed by an indented code block. The range() function is commonly used to iterate a specific number of times or through numerical indices. for loops are crucial for automating repetitive data processing tasks in pharmaceutical research.
Practice Exercise: Calculate Average Drug Concentration
You have a list of drug concentrations (in mg/L) measured at different time points for a new experimental drug. Write a Python for loop to calculate the sum of these concentrations and then compute the average concentration. Print both the total sum and the average concentration. drug_concentrations = [12.5, 15.2, 11.8, 13.0, 14.5, 10.9] # mg/L # Your code here: # Initialize a variable to store the sum # Loop through the concentrations, adding each to the sum # Calculate the average # Print the results
Watch the full lesson — free
This topic is part of Python for Pharmaceutical Research, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →