\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch % NOTE: do NOT define \bar -- it is the built-in LaTeX accent used by \bar{x}, % \bar{y} (sample means). Redefining it made those render as the word "bar". \newcommand\barunit{\unit{bar}} \end{aligned}\end{align} \]

Nov 16, 2026 | 1866 words | 19 min read

8.1.1. PCMs: Python Foundations#

This module introduces the core Python concepts you will use in ENGR 131. You will transition from writing cell formulas in Excel to writing structured, line-by-line programming scripts in Python

Before You Begin Python - Download the Software#

Use the Course Software page for detailed installation instructions and operating-system-specific guidance. Complete the following steps before you begin the following Python activities:

  1. Install Python or verify that Python is already installed on your computer.

  2. Install Visual Studio Code.

  3. Install the official Python extension in Visual Studio Code.

  4. Verify that Visual Studio Code is using the correct Python interpreter.

  5. Open and run the provided .py file in Visual Studio Code. Start with 00_hello_world.py.

Running Sequential Code#

Python is an interpreted programming language. This means the computer reads and executes your script sequentially, starting with the very first line at the top of the file and working down to the bottom.

If a line of code contains an error, the program stops immediately and does not execute any subsequent lines.

The simplest program prints output to the screen. Use the print() command to print output to the screen.

print("Hello World!")

Running Your First Python Program#

Practice

Download and open the 00_hello_world.py file to follow along with the video

Variables and Assignment Statements#

A variable is a named location in your computer’s memory that stores a value for later use. In programming, we use the assignment operator (=) to store data inside a variable.

# Store the baseline target voltage in volts
target_voltage = 3.3

The value on the right side of the = operator is evaluated first, and then stored inside the variable name on the left.

Variable Naming Standards#

To write professional code, you must follow strict naming rules:

  • Variable names must begin with a letter or an underscore (_).

  • They can only contain letters, numbers, and underscores.

  • They are case-sensitive (Sensor and sensor are two different variables).

  • They must be descriptive (use sensor_voltage instead of generic letters like x or y).

  • They cannot use Python reserved keywords (such as import, True, or print).

Basic Data Types#

Every value stored in a variable belongs to a specific data type. Python automatically determines the data type based on how you write the value:

Data Type

Description

Python Name

Example

Integer

Whole numbers without decimals

int

sensor_id = 101

Float

Numbers containing a decimal point

float

moisture_level = 0.38

String

Text characters enclosed in quotes

str

device_name = "Heart Monitor"

Boolean

Logical state of either True or False

bool

is_active = True

Data Type Conversion (Casting)#

Python automatically assigns data types to variables, but as an engineer, you will frequently need to force a value to change from one data type to another. This process is called casting.

Python provides built-in functions to convert values:

  • int(): Converts a float (by truncating the decimal) or a valid numeric string into a whole number.

  • float(): Converts an integer or a valid numeric string into a decimal number.

  • str(): Converts any value (including numbers and Booleans) into text characters.

  • bool(): Converts empty or zero values to False, and non-empty or non-zero values to True.

# Convert a float to an integer (note: this truncates, it does not round!)
measured_voltage = 3.84
truncated_voltage = int(measured_voltage)  # Returns 3

# Convert a Boolean to an integer (critical for non-selection logic)
is_active = True
binary_state = int(is_active)  # Returns 1

Casting a string with a decimal point directly to an integer will cause a runtime error. You must cast to a float first:

int("5.3")  # ValueError!
int(float("5.3"))  # Returns 5 (Valid)

Casting any non-empty string to a Boolean will return True, even if that string is “False” or “0”:

bool("False")  # Returns True!
bool("")       # Returns False

Mathematical Operators and Precedence#

Python uses standard operators to perform calculations within assignment statements:

Operation

Operator

Example Code

Addition

+

total_mass = casing_mass + sensor_mass

Subtraction

-

net_power = input_power - standby_power

Multiplication

*

total_charge = current * run_time

Division

/

average = sum_values/count
Note: always returns a float

Exponentiaition

**

area = 3.14159 * (radius ** 2)

Floor Division

//

completed_batches = total_hours // batch_time
Note: truncates to an integer

Modulus

%

remaining_seconds = total_seconds % 60
Note: returns the division remainder

Order of Operations#

Python follows standard algebraic order of operations. You must apply parentheses to group operations and ensure your calculations return the correct physical values:

  1. Parenthesis ()

  2. Exponents **

  3. Multiplication, Division, Modulus, and Floor Division (*, /, %, //)

  4. Addition and Subraction (+, -)

Reminder

If operators have equal precedence, Python evaluates them from left to right.

Basic Lists, Indexing, and Slicing#

A list is an ordered collection of values enclosed in square brackets ([]) and separated by commas. Lists allow you to store multiple related data points (like a sequence of sensor measurements) in a single variable.

# Create a list of five sensor temperature readings [deg C]
temperatures = [22.4, 25.1, 21.8, 24.3, 23.0]

Access Elements (0-Based Indexing)#

Python uses zero-based indexing to access individual elements in a list. This means the first element is at index 0, the second is at index 1, and so on:

first_temp = temperatures[0]   # Returns 22.4
second_temp = temperatures[1]  # Returns 25.1

You can also use negative indexing to access elements from the end of the list. Index -1 refers to the last element:

last_temp = temperatures[-1]   # Returns 23.0

Extracting Subsets (Slicing)#

To extract a subset of multiple elements from a list, use slicing syntax [start:stop]. The slice includes the element at the start index, but does not include the element at the stop index:

# Slice from index 2 up to (but not including) index 4
middle_temps = temperatures[2:4]  # Returns [21.8, 24.3]

Check for Understanding

Analyze the following Python list containing five sensor readings: readings = [10, 45, 60, 85, 100] subset = readings[1:4]

Which elements are stored in the variable subset?

A. 10, 45, 60
B. 45, 60, 85
C. 10, 45, 60, 85
D. 45, 60, 85, 100

Show Answer

Correct Answer: B
Slicing uses zero-based indexing and is exclusive of the stop index. readings[1:4] starts at index 1 (45) and goes up to but does not include index 4 (100). Therefore, it returns [45, 60, 85].

String Manipulation#

Engineers often need to process, clean, and format raw text data. Python provides several built-in operators and methods for strings.

String Concatenation (+)#

You can combine multiple strings together using the addition operator (+):

first_name = "Jane"
last_name = "Doe"
# Combine names with an underscore
folder_tag = last_name + "_" + first_name + "_"  # Returns "Doe_Jane_"

Casing Methods#

Strings have built-in methods to modify their capitalization:

  • .upper(): Converts all characters to uppercase.

  • .lower(): Converts all characters to lowercase.

  • .title(): Capitalizes the first letter of each word.

  • .capitalize(): Capitalizes only the very first letter of the entire string, forcing all other letters to lowercase.

raw_title = "biomedical engineer"
raw_name = "doe"

# Title case is perfect for multi-word professional titles
clean_title = raw_title.title()       # Returns "Biomedical Engineer"

# Capitalize is perfect for single names or sentences
clean_name = raw_name.capitalize()    # Returns "Doe"

String Splitting (.split())#

The .split() method splits a single string into a list of separate words based on spaces (or other specified characters):

words = clean_title.split()  # Returns ['Biomedical', 'Engineer']

Logical Comparisons and Boolean Indexing#

A comparison operator compares two values and returns a Boolean value (True or False).

average_score = 54.8
is_passing = average_score >= 50  # Returns True

Comparison Operators#

  • greater than > : returns True if the left operand is greater than the right operand

  • less than < : returns True if the left operand is less than the right operand

  • greater than or equal to >= : returns True if the left operand is greater than or equal to the right operand

  • less than or equal to <= : returns True if the left operand is less than or equal to the right operand

  • equal to == : returns True if the operands are equal

  • not equal to != : returns True if the operands are not equal

The Non-Selection Logic Trick (Boolean Indexing)#

When you need to make a logical decision (like determining if a device passed or failed) but cannot use an if statement, you can leverage Boolean Indexing.

In Python, logical Booleans behave like numbers when used as list indices:

  • False corresponds to 0

  • True corresponds to 1

By creating a list of status strings, you can use a comparison calculation to pull the correct label directly:

# Index 0 is "FAIL", Index 1 is "PASS"
status_options = ["FAIL", "PASS"]

# Calculate the passing boolean
is_passing = average_score >= 50  # Evaluates to True (which is 1)

# Retrieve the correct status string
final_status = status_options[is_passing]  # Returns "PASS"

Check for Understanding

Look at this code segment:

labels = ["FAIL", "PASS"]
test_val = 52.5
status = labels[test_val >= 60]

What is stored in the variable status?

A. PASS
B. FAIL
C. True
D. This code will result in an IndexError.

Show Answer

Correct Answer: B
The logical comparison test_val >= 60 evaluates to False (since 52.5 is less than 60). In Python, False is treated as integer index 0 when indexing lists. Therefore, labels is evaluated, which returns the string “FAIL”.

Gathering and Converting User Inputs#

To make programs interactive, use the input() function.

This function pauses the program and waits for the user to type a value on the keyboard:

# Gather the prototype name
prototype_name = input("Enter prototype name: ")

The input() function always returns user data as a string, even if the user types a number. You cannot perform mathematical operations on a string.

# This code will crash!
voltage_input = input("Enter sensor voltage [V]: ")
doubled_voltage = voltage_input * 2.0  # TypeError: Cannot multiply string by float

Input Conversions (Casting)#

To perform calculations on user inputs, you must explicitly convert (or “cast”) the input string into a numeric data type:

# Convert input to a whole integer
prototype_id = int(input("Enter prototype ID: "))

# Convert input to a decimal float
sensor_voltage = float(input("Enter sensor voltage [V]: "))

Formatting Printed Outputs#

To present your results clearly, use formatted string literals, commonly called f-strings.

An f-string begins with the letter f immediately before the opening quotation mark. Inside the string, place variables or calculations inside curly braces {}. Python evaluates the code inside the braces and prints the result as text:

sensor_temp = 22.8462
# Print a basic message
print(f"The sensor temperature is {sensor_temp} degrees Celsius.")

Controlling Numerical Precision#

To restrict the displayed output to meet engineering precision and significant figure conventions, append a format specifier (:.2f) inside the curly braces.

# Round the displayed temperature to exactly 2 decimal places
print(f"Sensor Temperature: {sensor_temp:.2f} [deg C]")
# Output: Sensor Temperature: 22.85 [deg C]
  • The : tells Python you are applying formatting rules.

  • The .2 specifies that you want to display exactly two digits after the decimal point.

  • The f establishes that you are formatting a floating-point number.

When limiting the number of decimal places, Python rounds the displayed value rather than truncating it. For example, 22.8462 formatted using .2f is displayed as 22.85, not 22.84. Note: The formatting changes only how the value is displayed. It does not change the value stored in sensor_temp; the variable still contains 22.8462.

Modules: Math and Random#

Python has built-in code libraries, called modules, that provide advanced mathematical functions and tools. To use them, you must import them at the top of your script.

The Math Module#

The math module provides standard mathematical constants and operations:

import math

# Calculate a square root
voltage_root = math.sqrt(24.8)

# Access the mathematical constant pi
circle_area = math.pi * (3.5 ** 2)

The Random Module#

The random module provides functions to generate pseudo-random numbers, which are essential for simulating experimental trials and material variability:

import random

# Initialize the random number generator with a seed value to ensure results are reproducible
random.seed(5)

# Generate a random integer between 5 and 100
random_measurement = random.randint(5, 100)

Some commonly used functions in the random module are:

random()    # generates a random float number between 0 and 1.
randint()   # generates a random integer number between two specified integers.
uniform()   # generates a random float number within a specified range.
seed()      # initializes the random number generator.
randrange() # generates a random integer number within a specified range with a step.
                # Syntax: random.randrange(start, stop, step)
choice()    # returns a random element from a sequence.
choices()   # returns a random sample of elements from a sequence with replacement.
sample()    # returns a random sample of elements from a sequence without replacement.
shuffle()   # shuffles the elements of a sequence.

Keywords and Reserved Words#

In Python, keywords are reserved words that have a predefined, built-in meaning within the language’s compiler. Because Python relies on these specific words to understand the structure of your program, you cannot use keywords as names for your variables, functions, or any other user-defined objects.

Rules for Keywords#

  • Case Sensitivity: Python keywords are strictly case-sensitive. For example, False is a reserved keyword, but false is not.

  • Fixed Count: Standard Python contains exactly 35 keywords. Examples include command words like import, structural identifiers like def, and logical operators like and or not.

  • Checking Keywords Programmatically: Instead of memorizing all 35 keywords, you can use Python’s built-in keyword module to view the complete list or verify if a name is safe to use: ``

import keyword

# Print the complete list of 35 reserved Python keywords
print(keyword.kwlist)

# Verify if a specific string is a reserved keyword (returns True or False)
print(keyword.iskeyword("break"))  # Output: True
print(keyword.iskeyword("voltage"))  # Output: False

Note: Attempting to assign a value to a keyword like break = 10 will result in a immediate SyntaxError: cannot assign to keyword.

Namespace Safety: Overwriting Built-In Functions#

A common mistake for beginner programmers is naming a variable after a built-in function (such as using print = 5, sum = 100, or type = "sensor"). Unlike keywords, Python will technically allow you to assign values to these names. However, doing so overwrites the built-in function in your program’s memory. If you name a variable print, you will destroy your script’s ability to output text, and calling print("Hello") later in your code will crash with a TypeError.

Checking for Built-In Names - to inspect the names reserved for standard functions and exceptions, you can import the builtins module and view its directory:

import builtins

# List all standard built-in functions and variables
print(dir(builtins))

Ensure your variable names do not match any function names returned in this list.

Check for Understanding

An engineer is trying to name variables for a blood pressure monitoring script. Which of the following code statements will execute successfully without causing a compilation or runtime error?

A. False = 0
B. false = 0
C. print = "Station_A"
D. import = True

Show Answer

Correct Answer: B
A is invalid because False is a reserved, case-sensitive Python keyword. You cannot assign values to keywords.
B is completely valid. Since keywords are case-sensitive, false (with a lowercase ‘f’) is treated as a standard, valid variable name.
C is syntactically allowed but highly dangerous. While it won’t throw an immediate syntax error, it overwrites Python’s built-in print() function. Any subsequent attempt to print text to the screen will crash the program.
D is invalid because import is a reserved structural keyword used to load modules.

ENGR 13100 Python Template#

Unless mentioned otherwise, you will use the ENGR 131 Python template for all Python assignments.

The Python template includes several components that you will use throughout this course:

  • Header information: The header information must always be edited to reflect the task your Python file is meant to solve.

  • File name: You will always be prompted in the problem statement to rename the Python file.

  • Import section: The template contains a designated section for importing modules.

  • main() function: The template contains a function called main(), where you will write your code. User-defined functions will be covered in more detail in the next Python module. For now, write all of your code within main().

Important: Code written inside a function must be indented one tab (or four spaces) relative to the indentation level of the function.

ENGR131_Python_Template.py