Lesson · 40 min · Free
Python While Loops
Python While Loops 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:
Python While Loops
Welcome to the "The Complete Python Bootcamp: Basics to Pharma & Data Science"! In this lesson, we will delve into the concept of while loops in Python. Loops are fundamental control flow structures that allow you to execute a block of code repeatedly. While for loops are excellent for iterating over sequences (like lists or strings), while loops are designed for situations where you need to repeat an action as long as a certain condition remains true. This is particularly useful in scientific programming when you might need to run simulations until a convergence criterion is met, or process data until a specific flag is encountered. A while loop continuously executes a block of statements as long as its controlling condition is True . The moment the condition becomes False , the loop terminates, and program execution continues with the statement immediately following the loop. It's crucial to ensure that the condition eventually becomes False , otherwise, you'll end up with an infinite loop , which will cause your program to run indefinitely and consume system resources.
Understanding the while Loop Syntax and Flow
The basic syntax of a while loop is straightforward: while condition: # Code to be executed repeatedly # (Make sure something inside the loop changes the condition to eventually become False) Let's break down the components: while keyword: This signifies the start of a while loop. condition: This is a boolean expression (something that evaluates to True or False ). The loop will continue to execute as long as this condition is True . Indented block: The code indented below the while statement is the "body" of the loop. This code will be executed in each iteration. Consider a simple example relevant to pharmaceutical calculations. Imagine we are trying to dilute a highly concentrated stock solution until it reaches a desired concentration. We might want to add a certain volume of diluent repeatedly until the target is met. # Example 1: Dilution simulation using a while loop initial_concentration_mM = 500 # Initial concentration in millimolar target_concentration_mM = 10 # Target concentration in millimolar current_concentration_mM = initial_concentration_mM diluent_volume_mL = 0 dilution_factor = 2 # Each step halves the concentration print(f"Starting dilution from {initial_concentration_mM} mM.") while current_concentration_mM > target_concentration_mM: current_concentration_mM /= dilution_factor # Halve the concentration diluent_volume_mL += 10 # Simulate adding 10 mL of diluent print(f"Current concentration: {current_concentration_mM:.2f} mM, Total diluent added: {diluent_volume_mL} mL") print(f"\nTarget concentration {target_concentration_mM} mM reached or exceeded. Final concentration: {current_concentration_mM:.2f} mM.") print(f"Total diluent added: {diluent_volume_mL} mL.") In this example, the loop continues as long as current_concentration_mM is greater than target_concentration_mM . Inside the loop, we simulate the dilution process and update the concentration. Crucially, the current_concentration_mM /= dilution_factor line ensures that the condition will eventually become False , preventing an infinite loop. Another common use case for while loops in data science or scientific computing is iterating until a specific convergence criterion is met, or processing a queue of items until it's empty. # Example 2: Processing a queue of patient samples patient_samples_to_process = ["Sample_A1", "Sample_B2", "Sample_C3", "Sample_D4", "Sample_E5"] processed_samples = [] max_samples_per_batch = 2 batch_number = 1 print(f"Initial samples to process: {patient_samples_to_process}") while patient_samples_to_process: # Loop continues as long as the list is not empty (evaluates to True) print(f"\n--- Processing Batch {batch_number} ---") current_batch = [] for _ in range(min(max_samples_per_batch, len(patient_samples_to_process))): sample = patient_samples_to_process.pop(0) # Remove and get the first sample current_batch.append(sample) processed_samples.append(sample) print(f" Processing {sample}...") print(f"Batch {batch_number} processed: {current_batch}") batch_number += 1 print(f"\nAll samples processed. Total processed: {len(processed_samples)}.") print(f"Remaining samples to process: {patient_samples_to_process}") Here, the condition while patient_samples_to_process: evaluates to True as long as the list patient_samples_to_process contains elements. An empty list evaluates to False in a boolean context, so the loop naturally terminates once all samples have been processed and removed from the list using .pop(0) .
Key Takeaways:
while loops execute a block of code repeatedly as long as a specified condition is True . They are ideal when the number of iterations is not known beforehand, but depends on a condition. Crucially, ensure the condition eventually becomes False to avoid infinite loops. Variables affecting the condition must be updated within the loop body. Commonly used for simulations, processing queues, or iterating until convergence.
Practice Exercise: Dosage Adjustment Simulation
A new drug's optimal dosage depends on a patient's body weight. The initial prescribed dose is 5 mg, and for every 10 kg over 60 kg, the dose needs to be increased by 0.5 mg. Write a Python program using a while loop that simulates calculating the adjusted dose for a patient, starting from an initial weight of 60 kg and incrementally increasing the weight by 5 kg until the adjusted dose exceeds 7 mg. Print the current weight and adjusted dose in each step.
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 →