Operators

Prerequisites:

  • Completed Module 1: Getting Started
  • Completed Lesson 2: Variables and Data Types
  • Basic understanding of Python variables

Learning Objectives

After completing this lesson, you will be able to:

  • Understand what operators are in Python.
  • Perform arithmetic calculations.
  • Use comparison operators to compare values.
  • Use logical operators to combine conditions.
  • Understand assignment operators.
  • Apply operators to medical imaging examples.
  • Build simple expressions using variables and operators.
  • Understand operator precedence.

Introduction

Programs often need to do more than store information.

For example, a medical imaging program may need to:

  • Calculate the total number of images.
  • Calculate image dimensions.
  • Compare two Hounsfield Unit (HU) values.
  • Determine whether contrast was used.
  • Calculate the average value of several measurements.
  • Check whether a slice thickness is within an expected range.

Python uses operators to perform these tasks.

An operator is a symbol or keyword that tells Python to perform an operation on one or more values.

For example:

number_of_slices = 300 
slice_thickness = 1.0 
total_coverage = number_of_slices * slice_thickness print(total_coverage)

Output:

300.0

Here, * is an operator that performs multiplication.

Operators are essential because they allow Python programs to calculate, compare, and make decisions.


Why Operators Matter

Imagine you are analyzing a CT examination.

You know:

number_of_slices = 400
slice_thickness = 0.625

You can calculate the approximate scan coverage:

scan_coverage = number_of_slices * slice_thickness print(scan_coverage)

Output:

250.0

Instead of manually calculating the value, Python performs the calculation for you.

This becomes especially useful when working with:

  • CT image dimensions
  • Pixel spacing
  • Slice thickness
  • Hounsfield Units
  • Image measurements
  • Patient age
  • Scan parameters
  • Image-processing calculations

What is an Operator?

An operator is a symbol or keyword used to perform an operation.

For example:

a = 10 
b = 5 
result = a + b 
print(result)

Output:

15

Here:

  • a is a variable.
  • b is a variable.
  • + is the operator.
  • result stores the answer.

The combination of values, variables, and operators forms an expression.

a + b

is an expression.


Types of Operators in Python

Python provides several types of operators.

The most important ones for beginners are:

  1. Arithmetic operators
  2. Comparison operators
  3. Logical operators
  4. Assignment operators
  5. Membership operators
  6. Identity operators

In this lesson, we will focus mainly on the first four because they are commonly used in medical imaging programs.


1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

Operator Description Example
+ Addition 10 + 5
- Subtraction 10 - 5
* Multiplication 10 * 5
/ Division 10 / 5
// Floor division 10 // 3
% Modulus 10 % 3
** Exponentiation 10 ** 2

Addition

The + operator adds two values.

number_of_images = 200 additional_images = 50 total_images = number_of_images + additional_images print(total_images)

Output:

250

Medical Imaging Example

Suppose two image series contain 300 and 200 images.

series_1 = 300 
series_2 = 200 
total_images = series_1 + series_2 
print(total_images)

Output:

500

Subtraction

The - operator subtracts one value from another.

initial_hu = 120
final_hu = 80 
difference = initial_hu - final_hu 
print(difference)

Output:

40

This could be useful when comparing measurements from different regions of an image.


Multiplication

The * operator multiplies values.

number_of_slices = 400 
slice_thickness = 0.625 
scan_coverage = number_of_slices * slice_thickness print(scan_coverage)

Output:

250.0

The result represents approximately 250 mm of image coverage if the simplified calculation assumes contiguous slices.


Division

The / operator performs division.

total_images = 500 
number_of_series = 5 
average_images = total_images / number_of_series print(average_images)

Output:

100.0

Notice that Python returns a floating-point number when using /.


Floor Division

The // operator performs floor division.

total_images = 10 
groups = 3 
result = total_images // groups 
print(result)

Output:

3

The decimal portion is discarded.

Floor division can be useful when dividing items into complete groups.


Modulus

The % operator returns the remainder after division.

total_images = 10 
groups = 3 
remainder = total_images % groups 
print(remainder)

Output:

1

Why?

10 ÷ 3 = 3 remainder 1

The modulus operator can be useful for determining whether a number is evenly divisible.

For example:

number_of_images = 512
print(number_of_images % 2)

Output:

262144

You can also use exponentiation:

number = 2 
result = number ** 3 
print(result)

Output:

8

2. Comparison Operators

Comparison operators are used to compare two values.

The result of a comparison is always a Boolean value:

True

or

False

Common comparison operators are:

Operator Meaning Example
== Equal to 5 == 5
!= Not equal to 5 != 3
> Greater than 5 > 3
< Less than 3 < 5
>= Greater than or equal to 5 >= 5
<= Less than or equal to 3 <= 5

Equal To

The == operator checks whether two values are equal.

slice_thickness = 1.0 
print(slice_thickness == 1.0)

Output:

True

Not Equal To

The != operator checks whether two values are different.

modality = “CT”

print(modality != “MRI”)

Output:

True

Greater Than

The > operator checks whether one value is greater than another.

hu_value = 150 
print(hu_value > 100)

Output:

True

Less Than

The < operator checks whether one value is smaller than another.

slice_thickness = 0.5 
print(slice_thickness < 1.0)

Output:

True

Greater Than or Equal To

The >= operator checks whether a value is greater than or equal to another value.

age= 65
print(age >= 65)

Output:

True

Less Than or Equal To

The <= operator checks whether a value is less than or equal to another value.

slice_thickness = 0.625 
print(slice_thickness <= 1.0)

Output:

True

Comparison Operators in Medical Imaging

Comparison operators are particularly important when analyzing medical imaging data.

For example:

hu_value = 120
print(hu_value > 100)

Output:

True

A program could use this comparison to identify whether a measured HU value is above a selected threshold.

Another example:

slice_thickness = 1.5 
print(slice_thickness <= 1.0)

Output:

False

This tells us that the slice thickness is greater than 1.0 mm.

This tells us that the slice thickness is greater than 1.0 mm.


3. Logical Operators

Logical operators allow us to combine multiple conditions.

Python provides three main logical operators:

Operator Meaning
and Both conditions must be True
or At least one condition must be True
not Reverses the result

The and Operator

The and operator returns True only when both conditions are true.

Example:

age = 50 
contrast_used = True 
result = age > 18 and contrast_used == True 
print(result)

Output:

True

and

contrast_used == True

The or Operator

The or operator returns True when at least one condition is true.

modality = "CT" 
result = modality == "CT" or modality == "MRI" print(result)

Output:

True

The first condition is true, so the entire expression is true.


The not Operator

The not operator reverses a Boolean value.

contrast_used = True 
print(not contrast_used)

Output:

False

Another example:

contrast_used = False 
print(not contrast_used)

Output:

True

4. Assignment Operators

Assignment operators are used to assign or update values.

The basic assignment operator is:

=

Example:

number_of_slices = 300

Python stores 300 in the variable number_of_slices.

There are also compound assignment operators.

Operator Example Equivalent
= x = 10 Assign
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5

Using +=

number_of_images = 100 
number_of_images += 50 
print(number_of_images)

Output:

150

This is equvalent to:

number_of_images = number_of_images + 50

Using -=

number_of_images = 500 
number_of_images -= 100 
print(number_of_images)

Output:

400

Using *=

slice_thickness = 0.5 
slice_thickness *= 2 
print(slice_thickness)

Output:

1.0
1.0

Expressions

An expression is a combination of values, variables, and operators that produces a result.

Example:

number_of_slices * slice_thickness

This is an expression.

For example:

number_of_slices = 400 
slice_thickness = 0.625
coverage = number_of_slices * slice_thickness print(coverage)

The expression:

number_of_slices * slice_thickness

produces:

250.0

Operator Precedence

When an expression contains multiple operators, Python follows a specific order.

For example:

result = 10 + 5 * 2 
print(result)

Output:

20

Why is the answer 20 instead of 30?

Python performs multiplication before addition.

5 × 2 = 10 
10 + 10 = 20

A useful beginner rule is:

  1. Parentheses ()
  2. Exponents **
  3. Multiplication, division, floor division, modulus
  4. Addition and subtraction
  5. Comparisons
  6. Logical operators

Using Parentheses

Parentheses can make the order of calculations clear.

result = (10 + 5) * 2 
print(result)

Output:

30

Python calculates:

10 + 5 = 15

Then:

10 + 5 = 15

Then:

15 × 2 = 30

Using parentheses is a good practice when calculations become complicated.


Practical Medical Imaging Example 1

Suppose a CT examination contains:

number_of_slices = 320 
slice_thickness = 0.75

Calculate the approximate scan coverage.

number_of_slices = 320 
slice_thickness = 0.75
scan_coverage = number_of_slices * slice_thickness print("Scan Coverage:", scan_coverage, "mm")

Output:

Scan Coverage: 240.0 mm

Practical Medical Imaging Example 2

Suppose an image has:

width = 512 
height = 512

Calculate the number of pixels.

width = 512 
height = 512
total_pixels = width * height 
print("Total Pixels:", total_pixels)

Output:

Total Pixels: 262144

Practical Medical Imaging Example 3

Suppose two regions of interest have HU measurements.

hu_region_1 = 45 
hu_region_2 = 80
difference = hu_region_2 - hu_region_1 print("HU Difference:", difference)

Output:

HU Difference: 35

Practical Medical Imaging Example 4

We can also compare an HU value with a threshold.

hu_value = 150 threshold = 100 above_threshold = hu_value > threshold 
print("Above Threshold:", above_threshold)

Output:

Above Threshold: True

This type of comparison becomes useful later when building image-analysis algorithms.


Practical Medical Imaging Example 5

We can combine multiple conditions.

Suppose we want to check whether:

  • The modality is CT.
  • The slice thickness is less than or equal to 1 mm.
modality = "CT" 
slice_thickness = 0.625 
result = modality == "CT" and slice_thickness <= 1.0 
print(result)

Output:

True

This demonstrates how logical operators can combine multiple pieces of information.


Common Beginner Mistakes

Mistake 1: Confusing = and ==

❌ Incorrect for comparison:

age = 50
print(age = 50)

✔ Correct:

age = 50
print(age == 50)

Remember:

=   Assignment
==  Comparison

Mistake 2: Forgetting the Difference Between / and //

print(10 / 3)

Output:

3.3333333333333335

While:

print(10 // 3)

Output:

3

Mistake 3: Using and Instead of or

Consider:

modality = "CT"

result = modality == "CT" and modality == "MRI"

This produces:

False

A value cannot be both "CT" and "MRI" at the same time.

If we want either condition to be true:

result = modality == "CT" or modality == "MRI"

Mistake 4: Ignoring Operator Precedence

Consider:

result = 10 + 5 * 2

The result is:

20

If you want addition first:

result = (10 + 5) * 2

The result is:

30

Best Practices

✔ Use parentheses when they make a calculation easier to understand.

✔ Use descriptive variable names.

✔ Use comparison operators carefully.

✔ Remember that = assigns a value while == compares values.

✔ Break complicated calculations into smaller expressions.

✔ Use logical operators to combine related conditions.

✔ Test calculations with simple values before using real clinical data.

✔ Remember that simplified examples may not represent the full complexity of clinical image analysis.



Mini Project: CT Examination Calculator

Create a small program that calculates basic information about a CT examination.

patient = "Sarah"

number_of_slices = 450
slice_thickness = 0.6

image_width = 512
image_height = 512

scan_coverage = number_of_slices * slice_thickness
pixels_per_image = image_width * image_height

print("Patient:", patient)
print("Scan Coverage:", scan_coverage, "mm")
print("Pixels per Image:", pixels_per_image)

Output:

Patient: Sarah
Scan Coverage: 270.0 mm
Pixels per Image: 262144

This simple project demonstrates how variables and operators work together.


Exercises

Exercise 1 – Basic Arithmetic

Create two variables:

a = 100
b = 25

Calculate and print:

  • Addition
  • Subtraction
  • Multiplication
  • Division

Exercise 2 – CT Scan Coverage

Create:

number_of_slices = 400
slice_thickness = 0.625

Calculate the approximate scan coverage.

Print the result in millimeters.


Exercise 3 – Image Dimensions

Create:

width = 512
height = 512

Calculate the total number of pixels in one image.


Exercise 4 – HU Comparison

Create:

hu_value = 120

Check whether the HU value is:

  • Greater than 100
  • Less than 100
  • Equal to 100

Print each result.


Exercise 5 – Logical Operators

Create:

modality = "CT"
contrast_used = True

Create an expression that checks whether:

  • The modality is CT and
  • Contrast was used.

Print the result.


Exercise 6 – Assignment Operators

Create:

number_of_images = 100

Use += to add 50 images.

Print the final number.


Exercise 7 – Medical Imaging

Create variables for:

patient_name
number_of_slices
slice_thickness
pixel_spacing
hu_value

Calculate:

  • Scan coverage
  • Whether the HU value is above 100
  • Total pixels for a 512 × 512 image

Display the results in a readable format.


Summary

In this lesson, you learned:

  • What operators are.
  • What expressions are.
  • How to perform arithmetic calculations.
  • How to use comparison operators.
  • How to use logical operators.
  • How assignment operators work.
  • How operator precedence affects calculations.
  • How operators can be applied to medical imaging examples.

The most important operators to remember are:

+    Addition
-    Subtraction
*    Multiplication
/    Division
//   Floor Division
%    Remainder
**   Power
==   Equal
!=   Not Equal
>    Greater Than
<    Less Than
>=   Greater Than or Equal
<=   Less Than or Equal
and  Both conditions
or   At least one condition
not  Reverse a condition

Operators are the tools that allow Python to calculate, compare, and reason about data.

As you progress through PyMedLab, these concepts will be used extensively when working with image dimensions, pixel values, DICOM metadata, Hounsfield Units, image processing, and AI algorithms.


What’s Next?

In the next lesson, Input and Output, you will learn how Python programs can interact with users.

You will learn how to:

  • Receive information using input().
  • Display information using print().
  • Format output.
  • Convert user input into numbers.
  • Build simple interactive medical imaging programs.

These skills will allow you to move from programs that simply perform predefined calculations to programs that can receive information and respond to the user.


Reference

  1. Brian Heinold, A Practical Introduction to Python Programming.
  2. Python Software Foundation, Python Documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *