Back to: Python for Medical Imaging
Understanding How to Organize and Reuse Python Code
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
- Basic understanding of Python variables and calculations
Learning Objectives
After completing this lesson, you will be able to:
- Understand what functions are.
- Explain why functions are useful.
- Create and define functions in Python.
- Call a function.
- Use parameters and arguments.
- Return values from functions.
- Use default parameters.
- Understand local and global variables at a beginner level.
- Apply functions to simple medical imaging examples.
- Build a small medical imaging program using functions.
Introduction
As Python programs become larger, writing all the instructions in one place can make the program difficult to understand and maintain.
Imagine that you repeatedly need to calculate CT scan coverage.
You could write:
coverage = number_of_slices * slice_thickness
every time you need the calculation.
However, if the same calculation is needed many times, it is better to create a function.
A function is a reusable block of code that performs a specific task.
For example:
def calculate_coverage(number_of_slices, slice_thickness):
return number_of_slices * slice_thickness
You can then use the function whenever you need it:
coverage = calculate_coverage(400, 0.625)
print(coverage)
Output:
250.0
Functions are one of the most important concepts in Python programming.
They help us create programs that are:
- Easier to read
- Easier to test
- Easier to maintain
- Easier to reuse
- More organized
Why Functions Matter
Consider a medical imaging program that performs several calculations.
It may need to:
- Calculate scan coverage.
- Calculate image dimensions.
- Calculate the average HU value.
- Check whether a slice thickness is acceptable.
- Display patient information.
Without functions, all of the code might be placed together.
With functions, each task can have its own section.
For example:
def calculate_coverage():
# code for scan coverage
def calculate_pixels():
# code for image pixels
def calculate_average_hu():
# code for HU calculation
This makes the program easier to understand.
What is a Function?
A function is a named, reusable block of code designed to perform a specific task.
A simple function looks like this:
def greet():
print("Hello")
Here:
deftells Python that we are defining a function.greetis the function name.()contains parameters, if any.:marks the beginning of the function body.- The indented code is executed when the function is called.
To use the function:
greet()
Output:
Hello
Defining a Function
The general structure is:
def function_name():
# instructions
For example:
def show_message():
print("Medical Imaging Program")
The function does not run simply because it has been defined.
We need to call it.
show_message()
Output:
Medical Imaging Program
Medical Imaging Program
Calling a Function
Calling a function means telling Python to execute the function.
Example:
def show_patient():
print("Patient: Sarah")
show_patient()
Output:
Patient: Sarah
We can call the same function more than once:
def show_patient():
print("Patient: Sarah")
show_patient()
show_patient()
Output:
Patient: Sarah
Patient: Sarah
This demonstrates one of the major advantages of functions: code reuse.
Functions with Parameters
A function can receive information from outside.
These inputs are called parameters.
Example:
def greet_patient(name):
print("Hello", name)
Now we can provide a name:
greet_patient("Sarah")
Output:
Hello Sarah
Here:
nameis the parameter."Sarah"is the argument passed to the function.
Parameters and Arguments
These two terms are closely related.
Consider:
def calculate_area(width, height):
return width * height
width and height are parameters.
When we call the function:
calculate_area(512, 512)
512 and 512 are arguments.
A simple way to remember:
Parameter: variable defined in the function.
Argument: value provided when calling the function.
Medical Imaging Example: Slice Coverage
We can create a function that calculates scan coverage.
def calculate_coverage(number_of_slices, slice_thickness):
coverage = number_of_slices * slice_thickness
return coverage
Call the function:
result = calculate_average(400, 0.625)
print(result)
Output:
250.0
We can use the same function with different CT examinations:
scan_1 = calculate_coverage(400, 0.625)
scan_2 = calculate_coverage(300, 1.0)
print(scan_1)
print(scan_2)
Output:
250.0
300.0
The function is written only once but can be used many times.
The return Statement
The return statement sends a value back from a function.
Example:
def add_numbers(a, b):
result = a + b
return result
Call the function:
answer = add_numbers(10, 5)
print(answer)
Output:
15
The function calculates the result and returns it.
We can then store the result in a variable.
print() vs return
Beginners often confuse print() and return.
Consider:
def add_numbers(a, b):
print(a + b)
This function displays the result.
Now consider:
def add_numbers(a, b):
return a + b
This function sends the result back to the program.
The returned value can then be used in another calculation.
For example:
def add_numbers(a, b):
return a + b
result = add_numbers(10, 5)
new_result = result * 2
print(new_result)
Output:
30
Using return makes a function much more reusable.
Function with Multiple Parameters
A function can have several parameters.
For example:
def patient_summary(name, age, modality):
print("Patient:", name)
print("Age:", age)
print("Modality:", modality)
Call the function:
patient_summary("John", 54, "CT")
Output:
Patient: John
Age: 54
Modality: CT
This is useful when a function needs several pieces of information.
Multiple Return Values
A Python function can return more than one value.
For example:
def calculate_image_size(width, height):
pixels = width * height
return width, height, pixels
Call the function:
width, height, pixels = calculate_image_size(512, 512)
print(width)
print(height)
print(pixels)
Output:
512
512
262144
This can be useful when a calculation produces several related results.
Default Parameters
A function can have a default value for a parameter.
Example:
def show_modality(modality="CT"):
print("Modality:", modality)
If no argument is provided:
show_modality()
Output:
Modality: CT
We can also provide another value:
show_modality("MRI")
Output:
Modality: MRI
Default parameters are useful when a value is commonly used but may sometimes change.
Medical Imaging Example: Default Slice Thickness
Suppose our program commonly works with a slice thickness of 1.0 mm.
def calculate_coverage(number_of_slices, slice_thickness=1.0):
return number_of_slices * slice_thickness
Now:
result = calculate_coverage(300)
print(result)
Output:
300.0
We can also specify another slice thickness:
result = calculate_coverage(300, 0.625)
print(result)
Output:
187.5
Functions and Data Types
Functions can accept different data types.
For example:
def show_patient(name, age):
print("Patient:", name)
print("Age:", age)
Call:
show_patient("Sarah", 45)
The function receives:
name → string
age → integer
Functions can also return different data types.
For example:
def get_modality():
return "CT"
The returned value is a string.
Another example:
def get_slice_thickness():
return 0.625
The returned value is a float.
Checking Function Results
We can use type() to check the type of a returned value.
def get_hu_value():
return 45
value = get_hu_value()
print(value)
print(type(value))
Output:
45
<class 'int'>
Local Variables
Variables created inside a function are generally local variables.
For example:
def calculate_coverage():
number_of_slices = 400
slice_thickness = 0.625
coverage = number_of_slices * slice_thickness
return coverage
The variables inside the function belong to that function’s local scope.
result = calculate_coverage()
print(result)
Output:
250.0
As a beginner, an important practice is to keep variables inside functions when they are only needed by that function.
Global Variables
A variable created outside a function is available in the surrounding program.
For example:
modality = "CT"
def show_modality():
print(modality)
show_modality()
Output:
CT
However, beginners should generally avoid relying heavily on global variables.
It is often better to pass information into a function using parameters.
For example:
def show_modality(modality):
print(modality)
show_modality("CT")
This makes the function more flexible and easier to reuse.
Functions Calling Other Functions
One function can call another function.
For example:
def calculate_coverage(slices, thickness):
return slices * thickness
def display_coverage(slices, thickness):
coverage = calculate_coverage(slices, thickness)
print("Scan Coverage:", coverage, "mm")
display_coverage(400, 0.625)
Output:
Scan Coverage: 250.0 mm
This allows larger programs to be divided into smaller tasks.
Practical Medical Imaging Example 1
Let’s create a function to calculate the total number of pixels in an image.
def calculate_pixels(width, height):
return width * height
Use the function:
pixels = calculate_pixels(512, 512)
print("Total Pixels:", pixels)
Output:
Total Pixels: 262144
Practical Medical Imaging Example 2
Let’s create a function to calculate the difference between two HU measurements.
def calculate_hu_difference(hu_1, hu_2):
return abs(hu_1 - hu_2)
Use it:
difference = calculate_hu_difference(45, 80)
print("HU Difference:", difference)
Output:
HU Difference: 35
The abs() function returns the absolute value, so the result is positive regardless of which value is larger.
Practical Medical Imaging Example 3
We can create a function to check whether a slice thickness is within a selected limit.
def acceptable_slice_thickness(slice_thickness):
return slice_thickness <= 1.0
Use it:
result = acceptable_slice_thickness(0.625)
print(result)
Output:
True
Try another value:
result = acceptable_slice_thickness(1.5)
print(result)
Output:
False
This is a simple example of how functions can return Boolean values.
Functions with Conditions
Functions can contain if statements.
For example:
def classify_hu(hu_value):
if hu_value < 0:
return "Below water reference"
elif hu_value == 0:
return "Approximately water"
else:
return "Above water reference"
Use the function:
result = classify_hu(50)
print(result)
Output:
Above water reference
This is a simplified educational example. Actual tissue classification in medical imaging is more complex and depends on many factors.
Functions and Repetition
Suppose we need to calculate scan coverage for several examinations.
Without a function:
scan_1 = 400 * 0.625
scan_2 = 300 * 1.0
scan_3 = 500 * 0.5
With a function:
def calculate_coverage(slices, thickness):
return slices * thickness
scan_1 = calculate_coverage(400, 0.625)
scan_2 = calculate_coverage(300, 1.0)
scan_3 = calculate_coverage(500, 0.5)
The second approach is easier to maintain.
If the calculation needs to change later, we only need to modify the function.
Built-in Functions
Python already provides many useful functions.
Some examples include:
print()
type()
len()
int()
float()
str()
abs()
round()
max()
min()
For example:
hu_values = [40, 50, 60]
print(max(hu_values))
Output:
60
And:
print(min(hu_values))
Output:
40
You will learn more about lists and collections in later lessons.
User-Defined Functions
Functions created by the programmer are called user-defined functions.
For example:
def calculate_scan_coverage(slices, thickness):
return slices * thickness
This is a user-defined function.
Python also provides built-in functions such as:
print()
and:
len()
Understanding the difference between built-in and user-defined functions will become increasingly important as your programs become more advanced.
Common Beginner Mistakes
Mistake 1: Forgetting to Call the Function
Defining a function does not automatically execute it.
def greet():
print("Hello")
Nothing is displayed until we call it:
greet()
Mistake 2: Forgetting Parentheses
❌
greet
✔
greet()
The parentheses tell Python to call the function.
Mistake 3: Forgetting return
Consider:
def add_numbers(a, b):
result = a + b
The function calculates the result but does not return it.
If we write:
answer = add_numbers(10, 5)
print(answer)
The result will be:
None
Correct:
def add_numbers(a, b):
result = a + b
return result
Mistake 4: Incorrect Indentation
Python uses indentation to define the function body.
❌ Incorrect:
def calculate():
print("Hello")
✔ Correct:
def calculate():
print("Hello")
Indentation is an essential part of Python syntax.
Mistake 5: Using the Wrong Number of Arguments
Consider:
def calculate_area(width, height):
return width * height
This function requires two arguments.
❌
calculate_area(512)
✔
calculate_area(512, 512)
Best Practices
✔ Give functions clear and descriptive names.
✔ Use snake_case for function names.
✔ Make each function perform one main task.
✔ Use parameters instead of unnecessary global variables.
✔ Use return when the result needs to be reused.
✔ Keep functions reasonably small and easy to understand.
✔ Add comments when the purpose of a function is not obvious.
✔ Use meaningful parameter names.
✔ Test functions with different input values.
✔ Avoid creating functions that perform too many unrelated tasks.
Mini Project: CT Examination Calculator
Let’s combine what we have learned into a small program.
def calculate_coverage(number_of_slices, slice_thickness):
return number_of_slices * slice_thickness
def calculate_pixels(width, height):
return width * height
def check_slice_thickness(slice_thickness):
return slice_thickness <= 1.0
patient_name = "Sarah"
number_of_slices = 450
slice_thickness = 0.6
image_width = 512
image_height = 512
coverage = calculate_coverage(
number_of_slices,
slice_thickness
)
pixels = calculate_pixels(
image_width,
image_height
)
acceptable = check_slice_thickness(
slice_thickness
)
print("Patient:", patient_name)
print("Scan Coverage:", coverage, "mm")
print("Pixels per Image:", pixels)
print("Slice Thickness Acceptable:", acceptable)
Output:
Patient: Sarah
Scan Coverage: 270.0 mm
Pixels per Image: 262144
Slice Thickness Acceptable: True
This program demonstrates an important programming concept:
A large task can be divided into smaller functions.
Exercises
Exercise 1 – Simple Function
Create a function called:
show_message()
The function should display:
Medical Imaging Program
Call the function.
Exercise 2 – Function with a Parameter
Create a function called:
show_patient(name)
The function should display the patient’s name.
Test it with:
show_patient("John")
Exercise 3 – Addition Function
Create a function called:
add_numbers(a, b)
The function should return the sum of the two numbers.
Test it with:
result = add_numbers(10, 20)
print(result)
Expected output:
30
Exercise 4 – CT Scan Coverage
Create a function called:
calculate_coverage(number_of_slices, slice_thickness)
Return the approximate scan coverage.
Test it using:
calculate_coverage(320, 0.75)
Expected result:
240.0
Exercise 5 – Image Dimensions
Create a function called:
calculate_pixels(width, height)
Return the total number of pixels.
Test it using:
calculate_pixels(512, 512)
Exercise 6 – HU Difference
Create a function called:
calculate_hu_difference(hu1, hu2)
Return the absolute difference between the two HU values.
Test it using:
calculate_hu_difference(45, 80)
Expected result:
35
Exercise 7 – Slice Thickness Check
Create a function that receives slice thickness and returns:
True
if the slice thickness is less than or equal to 1.0.
Otherwise, return:
False
Test the function with:
0.625
and:
1.5
Exercise 8 – Medical Imaging
Create functions for:
- Calculating scan coverage
- Calculating total pixels
- Checking slice thickness
- Calculating HU difference
Then create a small CT examination program that uses all four functions.
Use:
patient_name = "Emily"
number_of_slices = 400
slice_thickness = 0.625
image_width = 512
image_height = 512
hu_1 = 45
hu_2 = 80
Display the results in a readable format.
Summary
In this lesson, you learned:
- What functions are.
- Why functions are useful.
- How to define a function using
def. - How to call a function.
- How to pass arguments to a function.
- How to use parameters.
- How to return values using
return. - How to use default parameters.
- The basic difference between local and global variables.
- How functions can call other functions.
- How functions can be applied to medical imaging problems.
The basic structure of a function is:
def function_name(parameters):
# instructions
return result
For example:
def calculate_coverage(slices, thickness):
return slices * thickness
Functions allow us to turn repeated calculations and tasks into reusable pieces of code.
They are an essential foundation for larger Python programs.
As you continue through PyMedLab, you will use functions to work with:
- DICOM metadata
- CT image data
- Hounsfield Units
- Image-processing operations
- Patient and examination information
- Machine-learning workflows
- Medical imaging AI applications

Leave a Reply