Back to: Python for Medical Imaging
Learning How Python Repeats Tasks Automatically
Difficulty: Beginner
Reading Time: 20–25 minutes
Prerequisites:
- Completed Module 1: Getting Started
- Completed Lesson 2: Variables and Data Types
- Completed Lesson 3: Operators and Expressions
- Completed Lesson 5: Input and Output
- Completed Lesson 6: Conditional Statements
- Basic understanding of variables and conditions
Learning Objectives
After completing this lesson, you will be able to:
- Understand why loops are used in programming.
- Understand the concept of repetition.
- Use for loops.
- Use while loops.
- Use the range() function.
- Understand loop variables.
- Combine loops with conditional statements.
- Use break and continue.
- Calculate values repeatedly.
- Process multiple medical imaging measurements.
- Apply loops to simple medical imaging examples.
Introduction
Computers are very good at repeating tasks.
Imagine you have 500 CT images and want to perform the same operation on every image.
You could write:
process(image1)
process(image2)
process(image3)
But what if you have:
500 images
5,000 images
500,000 images
Writing the same instruction thousands of times would be inefficient and difficult to maintain.
Python provides loops to solve this problem.
A loop allows a program to repeat a block of code automatically.
For example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Instead of writing five print() statements, we write one loop.
Why Loops Matter
Loops are extremely important in medical imaging and data analysis.
A medical imaging application may need to:
- Process every CT slice.
- Examine every image in a study.
- Analyze multiple HU measurements.
- Calculate statistics from image data.
- Check multiple image dimensions.
- Process pixels in an image.
- Read multiple files.
- Apply the same operation to many patients or studies.
The general idea is:
One operation
↓
Repeat
↓
Repeat
↓
Repeat
↓
Many operations
Loops allow Python to perform repetitive tasks efficiently.
What is a Loop?
A loop is a programming structure that repeats a block of code.
For example:
for i in range(3):
print("CT")
Output:
CT
CT
CT
The print() statement is executed three times.
Types of Loops in Python
Python has two main types of loops:
1. for loop
Used when you want to repeat something for each item in a sequence or for a known number of times.
Example:
for i in range(5):
print(i)
2. while loop
Used when you want to continue repeating something while a condition remains true.
Example:
count = 0
while count < 5:
print(count)
count += 1
Both are important, but they are used in slightly different situations.
The for Loop
The for loop is one of the most commonly used loops in Python.
Basic structure:
for variable in sequence:
# code to repeat
For example:
for number in [1, 2, 3, 4]:
print(number)
Output:
1
2
3
4
Python takes each item from the list and assigns it to number.
Understanding the Loop Variable
Consider:
for number in [1, 2, 3]:
print(number)
The loop works approximately like this:
First iteration → number = 1
Second iteration → number = 2
Third iteration → number = 3
The word number is simply a variable name.
We could use another name:
for value in [1, 2, 3]:
print(value)
The result is the same.
It is best to choose a meaningful name.
Using range()
The range() function is frequently used with for loops.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Notice that the sequence starts at 0 and stops before 5.
This is an important feature of range().
Understanding range()
range(5)
produces:
0, 1, 2, 3, 4
It does not include 5.
Similarly:
range(10)
produces:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Why Does Python Start at Zero?
Python, like many programming languages, uses zero-based indexing.
This becomes especially important when working with:
- Lists
- Arrays
- Image pixels
- Image slices
- DICOM data
- Machine learning datasets
For example:
for slice_number in range(5):
print(slice_number)
Output:
0
1
2
3
4
There are five values, but the first index is 0.
Specifying a Starting Value
We can give range() a start and stop value.
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
The structure is:
range(start, stop)
The stop value is not included.
Using a Step
We can also specify a step.
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
The structure is:
range(start, stop, step)
Counting Backwards
A negative step can be used to count backwards.
for i in range(5, 0, -1):
print(i)
Output:
5
4
3
2
1
This can be useful for countdowns or reverse processing.
Repeating a Message
A simple example:
for i in range(5):
print("Medical Imaging")
Output:
Medical Imaging
Medical Imaging
Medical Imaging
Medical Imaging
Medical Imaging
The loop repeats the same instruction five times.
Using the Loop Variable
The loop variable can be used inside the loop.
for i in range(5):
print("Image:", i)
Output:
Image: 0
Image: 1
Image: 2
Image: 3
Image: 4
This is useful when processing numbered images or slices.
Medical Imaging Example: CT Slices
Suppose a CT examination contains five slices.
for slice_number in range(5):
print("Processing slice:", slice_number)
Output:
Processing slice: 0
Processing slice: 1
Processing slice: 2
Processing slice: 3
Processing slice: 4
The same operation could be performed on every slice.
Starting Slice Number at 1
Sometimes we want the user-facing slice numbers to start at 1.
for slice_number in range(1, 6):
print("Processing slice:", slice_number)
Output:
Processing slice: 1
Processing slice: 2
Processing slice: 3
Processing slice: 4
Processing slice: 5
This is often easier to understand when displaying information to users.
Remember that internally, many Python data structures use zero-based indexing.
Looping Through a List
Loops can process each item in a list.
For example:
modalities = ["CT", "MRI", "X-ray"]
for modality in modalities:
print(modality)
Output:
CT
MRI
X-ray
The loop processes each item one at a time.
Medical Imaging Example: Multiple Modalities
modalities = [
"CT",
"MRI",
"X-ray",
"Ultrasound"
]
for modality in modalities:
print("Modality:", modality)
Output:
Modality: CT
Modality: MRI
Modality: X-ray
Modality: Ultrasound
This is useful when working with collections of imaging studies or modality names.
Looping Through HU Values
Suppose we have several HU measurements:
hu_values = [45, 50, 52, 48, 55]
for hu in hu_values:
print("HU:", hu)
Output:
HU: 45
HU: 50
HU: 52
HU: 48
HU: 55
Each HU value is processed individually.
Calculating with a Loop
We can perform calculations inside a loop.
hu_values = [45, 50, 52, 48, 55]
for hu in hu_values:
adjusted_value = hu + 10
print(adjusted_value)
Output:
55
60
62
58
65
The same calculation is performed for every value.
Using Conditions Inside Loops
Loops and conditional statements are often used together.
For example:
hu_values = [45, 150, 80, 200, 30]
for hu in hu_values:
if hu > 100:
print(hu, "is above 100")
Output:
150 is above 100
200 is above 100
The loop examines every value, while the if statement decides whether to display it.
Medical Imaging Example: Checking HU Values
hu_values = [-50, 0, 25, 75, 120, 200]
for hu in hu_values:
if hu < 0:
print(hu, "is below 0 HU")
elif hu == 0:
print(hu, "is approximately 0 HU")
else:
print(hu, "is above 0 HU")
Output:
-50 is below 0 HU
0 is approximately 0 HU
25 is above 0 HU
75 is above 0 HU
120 is above 0 HU
200 is above 0 HU
This demonstrates how loops and conditions can work together.
The while Loop
The second major loop in Python is the while loop.
A while loop repeats code while a condition is true.
Basic structure:
while condition:
# code to repeat
Example:
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Understanding the while Loop
The program starts with:
count = 0
Then Python checks:
count < 5
Because this is true, the loop runs.
Then:
count += 1
changes the value.
The process continues:
count = 0 → True → print
count = 1 → True → print
count = 2 → True → print
count = 3 → True → print
count = 4 → True → print
count = 5 → False → stop
Important: Avoiding Infinite Loops
Consider:
count = 0
while count < 5:
print(count)
This is dangerous because count never changes.
The condition:
count < 5
will remain true forever.
This creates an infinite loop.
Correct:
count = 0
while count < 5:
print(count)
count += 1
Always make sure a while loop can eventually become false.
Using while for User Input
A while loop can continue asking for information until a condition is met.
For example:
age = int(input("Enter an age greater than 0: "))
while age <= 0:
print("Invalid age.")
age = int(input("Enter an age greater than 0: "))
print("Age accepted:", age)
This is an example of basic input validation.
Medical Imaging Example: Validating Slice Thickness
slice_thickness = float(
input("Enter slice thickness in mm: ")
)
while slice_thickness <= 0:
print("Slice thickness must be greater than 0.")
slice_thickness = float(
input("Enter slice thickness in mm: ")
)
print("Slice thickness accepted:", slice_thickness)
The program continues asking until the user enters a positive value.
This is a simple example of validation.
for Loop vs while Loop
The two loops are used for different situations.
| Loop | Common Use |
| for | Repeat for each item |
| for | Repeat a known number of times |
| while | Repeat while a condition is true |
| while | Continue until a condition changes |
For example:
Use for:
for i in range(10):
print(i)
when you know you want ten repetitions.
Use while:
while value < 100:
value += 10
when the number of repetitions depends on a condition.
The break Statement
Sometimes we want to stop a loop early.
Python provides break.
Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
When i reaches 5, the loop stops.
Medical Imaging Example with break
Suppose we are searching for a particular HU value.
hu_values = [20, 35, 50, 100, 150, 200]
for hu in hu_values:
print("Checking:", hu)
if hu >= 100:
print("Threshold reached.")
break
Output:
Checking: 20
Checking: 35
Checking: 50
Checking: 100
Threshold reached.
The loop stops as soon as the condition is satisfied.
The continue Statement
The continue statement skips the current iteration and moves to the next one.
Example:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
The value 2 is skipped.
Medical Imaging Example with continue
Suppose we want to skip invalid negative values.
hu_values = [45, -999, 50, 60, -999, 80]
for hu in hu_values:
if hu == -999:
continue
print("HU:", hu)
Output:
HU: 45
HU: 50
HU: 60
HU: 80
Here -999 is treated as a placeholder for missing or invalid data.
In real datasets, missing-value conventions depend on the dataset and should be handled explicitly.
Calculating a Total with a Loop
A common use of loops is calculating totals.
For example:
values = [10, 20, 30, 40]
total = 0
for value in values:
total = total + value
print("Total:", total)
Output:
Total: 100
The variable total keeps track of the accumulated value.
Using +=
The previous example can be shortened.
Instead of:
total = total + value
we can write:
total += value
Example:
values = [10, 20, 30, 40]
total = 0
for value in values:
total += value
print("Total:", total)
Output:
Total: 100
Calculating Average HU
Loops can be used to calculate a simple average.
hu_values = [40, 50, 60, 70, 80]
total = 0
for hu in hu_values:
total += hu
average = total / len(hu_values)
print("Average HU:", average)
Output:
Average HU: 60.0
Here:
len(hu_values)
returns the number of values.
Medical Imaging Example: Average Measurement
Suppose we have measurements from several regions:
measurements = [45.2, 47.1, 44.8, 46.5, 45.9]
total = 0
for value in measurements:
total += value
average = total / len(measurements)
print(f"Average measurement: {average:.2f}")
Output:
Average measurement: 45.90
This demonstrates how loops can support basic data analysis.
Finding the Maximum Value
We can also use a loop to find the largest value.
hu_values = [45, 120, 80, 200, 60]
maximum = hu_values[0]
for hu in hu_values:
if hu > maximum:
maximum = hu
print("Maximum HU:", maximum)
Output:
Maximum HU: 200
Python also provides built-in functions such as max(), but understanding the loop helps you understand how the process works.
Finding the Minimum Value
Similarly:
hu_values = [45, 120, 80, 200, 60]
minimum = hu_values[0]
for hu in hu_values:
if hu < minimum:
minimum = hu
print("Minimum HU:", minimum)
Output:
Minimum HU: 45
Nested Loops
A loop can contain another loop.
This is called a nested loop.
Example:
for row in range(3):
for column in range(3):
print(row, column)
Output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Nested loops are especially important when working with two-dimensional structures.
For example, an image can be represented conceptually as:
Row 0 → Pixel Pixel Pixel
Row 1 → Pixel Pixel Pixel
Row 2 → Pixel Pixel Pixel
A nested loop can process rows and columns.
Medical Imaging Example: Image Pixels
For educational purposes, imagine a small 3 × 3 image:
image = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
We can process every value:
for row in image:
for pixel in row:
print(pixel)
Output:
10
20
30
40
50
60
70
80
90
This concept becomes very important when working with actual image arrays using libraries such as NumPy.
Using a Loop to Process Image Rows
We can also calculate the sum of all pixels:
image = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
total = 0
for row in image:
for pixel in row:
total += pixel
print("Total:", total)
Output:
Total: 450
This is a simplified example of image-data processing.
In real medical imaging applications, numerical libraries such as NumPy are normally used instead of manually processing large images with Python loops.
Combining Loops, Conditions, and Functions
We can combine several concepts into one program.
For example:
def count_high_hu(values, threshold):
count = 0
for value in values:
if value > threshold:
count += 1
return count
hu_values = [40, 150, 80, 200, 120]
result = count_high_hu(hu_values, 100)
print("Values above threshold:", result)
Output:
Values above threshold: 3
This program uses:
- A function
- A loop
- A condition
- Variables
- A list
- A counter
- A return value
These concepts will become increasingly important as you progress through PyMedLab.
Common Beginner Mistakes
Mistake 1: Forgetting Indentation
❌
for i in range(5):
print(i)
✔
for i in range(5):
print(i)
Mistake 2: Forgetting the Colon
❌
for i in range(5)
print(i)
✔
for i in range(5):
print(i)
Mistake 3: Expecting range(5) to Include 5
for i in range(5):
print(i)
produces:
0
1
2
3
4
It does not produce 5.
If you want 0 through 5:
for i in range(6):
print(i)
Mistake 4: Creating an Infinite while Loop
❌
count = 0
while count < 5:
print(count)
count never changes.
✔
count = 0
while count < 5:
print(count)
count += 1
Mistake 5: Changing the Wrong Variable
Consider:
count = 0
while count < 5:
print(count)
number = count + 1
The variable count never changes.
Correct:
count = 0
while count < 5:
print(count)
count += 1
Mistake 6: Confusing break and continue
break:
Stops the entire loop.
continue:
Skips the current iteration.
For example:
for i in range(5):
if i == 2:
break
print(i)
stops the loop.
Whereas:
for i in range(5):
if i == 2:
continue
print(i)
skips only 2.
Best Practices
✔ Use meaningful loop variable names.
✔ Keep loop bodies simple and readable.
✔ Use for when processing a sequence or a known number of repetitions.
✔ Use while when repetition depends on a condition.
✔ Make sure while loops can eventually terminate.
✔ Use break when you genuinely need to stop early.
✔ Use continue when you need to skip specific items.
✔ Avoid unnecessary nested loops.
✔ For large medical image arrays, learn to use optimized numerical libraries such as NumPy rather than relying on slow Python-level loops for every pixel.
✔ Test loops with small datasets before applying them to large datasets.
Mini Project: CT Slice Processing
Let’s create a simple program that simulates processing CT slices.
number_of_slices = int(
input(“Enter number of slices: “)
)
for slice_number in range(1, number_of_slices + 1):
print(f”Processing slice {slice_number}”)
print(“Processing complete.”)
Example:
Enter number of slices: 5
Processing slice 1
Processing slice 2
Processing slice 3
Processing slice 4
Processing slice 5
Processing complete.
This is a simplified simulation. A real CT processing program would perform operations on actual image data.
Mini Project 2: HU Analysis
Let’s create a small program that processes multiple HU measurements.
hu_values = [45, 80, 120, 150, 30, 200]
total = 0
high_values = 0
for hu in hu_values:
total += hu
if hu > 100:
high_values += 1
average = total / len(hu_values)
print(“HU Analysis”)
print(“———–“)
print(f”Number of measurements: {len(hu_values)}”)
print(f”Average HU: {average:.2f}”)
print(f”Values above 100 HU: {high_values}”)
Output:
HU Analysis
———–
Number of measurements: 6
Average HU: 104.17
Values above 100 HU: 3
This demonstrates how a loop can process a collection of measurements.
Mini Project 3: Interactive HU Collection
We can also combine a loop with input().
number_of_values = int(
input(“How many HU values will you enter? “)
)
total = 0
for i in range(number_of_values):
hu = float(
input(f”Enter HU value {i + 1}: “)
)
total += hu
average = total / number_of_values
print()
print(“HU Analysis”)
print(“———–“)
print(f”Number of values: {number_of_values}”)
print(f”Average HU: {average:.2f}”)
Example:
How many HU values will you enter? 3
Enter HU value 1: 40
Enter HU value 2: 50
Enter HU value 3: 60
HU Analysis
———–
Number of values: 3
Average HU: 50.00
This program demonstrates:
Input
↓
Loop
↓
Conversion
↓
Calculation
↓
Output
Exercises
Exercise 1 – Basic for Loop
Write a for loop that prints the numbers:
1
2
3
4
5
Exercise 2 – CT Slices
Write a loop that displays:
Processing slice 1
Processing slice 2
Processing slice 3
…
Processing slice 10
Exercise 3 – Even Numbers
Use range() to print the even numbers from 0 to 20.
Expected output:
0
2
4
6
…
20
Exercise 4 – HU Values
Create:
hu_values = [20, 40, 60, 80, 100]
Use a for loop to print each value.
Exercise 5 – HU Threshold
Using:
hu_values = [20, 150, 80, 200, 50]
Use a loop and an if statement to print only values greater than 100.
Exercise 6 – Calculate an Average
Create a list of five numerical measurements.
Use a loop to calculate their total and then calculate the average.
Display the average to two decimal places.
Exercise 7 – while Loop
Create a program that starts with:
count = 1
and uses a while loop to print:
1
2
3
4
5
Exercise 8 – Input Validation
Ask the user to enter a positive number.
Continue asking while the number is less than or equal to zero.
Display:
Value accepted.
when a valid value is entered.
Exercise 9 – Image Dimensions
Create a small 2D image:
image = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
Use nested loops to print every pixel value.
Exercise 10 – Medical Imaging Challenge
Create a program that:
- Asks the user how many HU values they want to enter.
- Uses a for loop to collect the values.
- Calculates the total.
- Calculates the average.
- Finds how many values are above 100 HU.
- Displays the results in a readable format.
Try to organize your program using a function.
Summary
In this lesson, you learned:
- What loops are.
- Why repetition is important in programming.
- How to use for loops.
- How to use while loops.
- How range() works.
- How to loop through lists.
- How to use loops with conditions.
- How to use break.
- How to use continue.
- How to calculate totals and averages with loops.
- How to use nested loops.
- How loops can be applied to medical imaging data.
- How loops, functions, conditions, and input/output can work together.
The basic for loop is:
for item in sequence:
# repeat this code
The basic while loop is:
while condition:
# repeat this code
A useful way to remember the difference is:
FOR
↓
“For each item, do something.”
WHILE
↓
“While this condition is true, keep doing something.”
Loops are one of the most important programming concepts because they allow Python to process large amounts of information without repeating code manually.
In medical imaging, this becomes especially important when dealing with:
Patients
↓
Studies
↓
Series
↓
Images
↓
Slices
↓
Rows
↓
Pixels
The ability to repeat operations efficiently is fundamental to image processing and data analysis.
What’s Next?
In the next lesson, Lists and Collections, you will learn how Python stores multiple pieces of information together.
You will learn about:
- Lists
- Indexing
- Accessing elements
- Adding and removing items
- Updating values
- List methods
- Looping through lists
- Lists of medical imaging measurements
For example:
hu_values = [45, 52, 60, 75, 100]
Instead of storing each value in a separate variable:
hu_1 = 45
hu_2 = 52
hu_3 = 60
hu_4 = 75
hu_5 = 100
we can store them together.
This will provide an important foundation for working with image data, DICOM metadata, datasets, NumPy arrays, and machine learning later in PyMedLab.
References
- Brian Heinold, A Practical Introduction to Python Programming.
- Python Software Foundation, Python Documentation.

Leave a Reply