Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Appendix A: Python Programming Essentials for Engineers

Authors
Affiliations
University of Alberta
University of Alberta

A.1 Introduction

This appendix provides essential Python programming knowledge for engineering students. We’ll cover fundamental concepts progressively, from basic variables to scientific computing with NumPy and visualization with Matplotlib. Each concept builds upon previous ones, so work through sections sequentially.

Why Python for Engineering?


A.2 Variables and Data Types

A.2.1 Creating Variables

Variables store data values. Python automatically determines the data type.

Name: John
Age: 25
Height: 5.9
Is student: True

A.2.2 Data Types

Python has several built-in data types:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
x: 123 (type: <class 'str'>)
y: 123 (type: <class 'int'>)
z: 123.0 (type: <class 'float'>)
w: 456 (type: <class 'str'>)

A.2.3 Variable Naming Rules


A.3 Basic Operations

A.3.1 Arithmetic Operations

10 + 3 = 13
10 / 3 = 3.3333333333333335
10 ** 3 = 1000

A.3.2 Comparison Operations

5 == 10: False
5 != 10: True
5 < 10: True
5 > 10: False
5 <= 10: True
5 >= 10: False

A.3.3 String Operations

Full name: John Johnson
Hello, I'm John and I'm 22 years old.
Original: '  Python Programming  '
Uppercase:   PYTHON PROGRAMMING  
Lowercase:   python programming  
Stripped: Python Programming
Length: 22

A.4 Control Structures

A.4.1 Conditional Statements (if/elif/else)

It's warm.
WARNING: High stress level
Safety factor: 1.20

A.4.2 For Loops

Counting from 1 to 5:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Available sensors:
- accelerometer
- strain gauge
- GPS
- temperature

Sensors with numbers:
1. accelerometer
2. strain gauge
3. GPS
4. temperature

Load Analysis:
Load 1: 100 kN, Moment: 200 kN⋅m
Load 2: 150 kN, Moment: 600 kN⋅m
Load 3: 200 kN, Moment: 1200 kN⋅m
Load 4: 175 kN, Moment: 1400 kN⋅m
Load 5: 125 kN, Moment: 1250 kN⋅m

Figure 1:Demonstrating for loops with range, lists, enumerate, and engineering load analysis

A.4.3 While Loops

Output
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Iterative solution:
Iteration 1: Error = 0.100000
Iteration 2: Error = 0.110000
Iteration 3: Error = 0.120000
Iteration 4: Error = 0.130000
Iteration 5: Error = 0.140000
Iteration 6: Error = 0.150000
Iteration 7: Error = 0.160000
Iteration 8: Error = 0.170000
Iteration 9: Error = 0.180000
Iteration 10: Error = 0.190000
Iteration 11: Error = 0.200000
Iteration 12: Error = 0.210000
Iteration 13: Error = 0.220000
Iteration 14: Error = 0.230000
Iteration 15: Error = 0.240000
Iteration 16: Error = 0.250000
Iteration 17: Error = 0.260000
Iteration 18: Error = 0.270000
Iteration 19: Error = 0.280000
Iteration 20: Error = 0.290000
Iteration 21: Error = 0.300000
Iteration 22: Error = 0.310000
Iteration 23: Error = 0.320000
Iteration 24: Error = 0.330000
Iteration 25: Error = 0.340000
Iteration 26: Error = 0.350000
Iteration 27: Error = 0.360000
Iteration 28: Error = 0.370000
Iteration 29: Error = 0.380000
Iteration 30: Error = 0.390000
Iteration 31: Error = 0.400000
Iteration 32: Error = 0.410000
Iteration 33: Error = 0.420000
Iteration 34: Error = 0.430000
Iteration 35: Error = 0.440000
Iteration 36: Error = 0.450000
Iteration 37: Error = 0.460000
Iteration 38: Error = 0.470000
Iteration 39: Error = 0.480000
Iteration 40: Error = 0.490000
Iteration 41: Error = 0.500000
Iteration 42: Error = 0.510000
Iteration 43: Error = 0.520000
Iteration 44: Error = 0.530000
Iteration 45: Error = 0.540000
Iteration 46: Error = 0.550000
Iteration 47: Error = 0.560000
Iteration 48: Error = 0.570000
Iteration 49: Error = 0.580000
Iteration 50: Error = 0.590000
Iteration 51: Error = 0.600000
Iteration 52: Error = 0.610000
Iteration 53: Error = 0.620000
Iteration 54: Error = 0.630000
Iteration 55: Error = 0.640000
Iteration 56: Error = 0.650000
Iteration 57: Error = 0.660000
Iteration 58: Error = 0.670000
Iteration 59: Error = 0.680000
Iteration 60: Error = 0.690000
Iteration 61: Error = 0.700000
Iteration 62: Error = 0.710000
Iteration 63: Error = 0.720000
Iteration 64: Error = 0.730000
Iteration 65: Error = 0.740000
Iteration 66: Error = 0.750000
Iteration 67: Error = 0.760000
Iteration 68: Error = 0.770000
Iteration 69: Error = 0.780000
Iteration 70: Error = 0.790000
Iteration 71: Error = 0.800000
Iteration 72: Error = 0.810000
Iteration 73: Error = 0.820000
Iteration 74: Error = 0.830000
Iteration 75: Error = 0.840000
Iteration 76: Error = 0.850000
Iteration 77: Error = 0.860000
Iteration 78: Error = 0.870000
Iteration 79: Error = 0.880000
Iteration 80: Error = 0.890000
Iteration 81: Error = 0.900000
Iteration 82: Error = 0.910000
Iteration 83: Error = 0.920000
Iteration 84: Error = 0.930000
Iteration 85: Error = 0.940000
Iteration 86: Error = 0.950000
Iteration 87: Error = 0.960000
Iteration 88: Error = 0.970000
Iteration 89: Error = 0.980000
Iteration 90: Error = 0.990000
Iteration 91: Error = 1.000000
Iteration 92: Error = 1.010000
Iteration 93: Error = 1.020000
Iteration 94: Error = 1.030000
Iteration 95: Error = 1.040000
Iteration 96: Error = 1.050000
Iteration 97: Error = 1.060000
Iteration 98: Error = 1.070000
Iteration 99: Error = 1.080000
Iteration 100: Error = 1.090000
Maximum iterations reached

A.5 Functions

A.5.1 Defining Functions

Hello, Alice!
Area: 15
Volume 1: 15.0
Volume 2: 30

Figure 2:Demonstrating function definitions with parameters, defaults, and engineering calculations

A.5.2 Engineering Functions

Applied force: 10000 N
Cross-sectional area: 0.01 m²
Calculated stress: 1.00 MPa
Safety factor: 250.00

A.5.3 Lambda Functions (Anonymous Functions)

Square of 5: 25
Sum of 3 and 4: 7
Numbers: [1, 4, 9, 16, 25]
Square roots: [1.0, 2.0, 3.0, 4.0, 5.0]
Even numbers: [2, 4, 6, 8, 10]

A.6 Data Structures

A.6.1 Lists

First measurement: 1.2
Last measurement: 2.9
Second sensor: strain
First 3 measurements: [1.2, 2.5, 3.1]
Last 2 measurements: [4.8, 2.9]
Every second measurement: [1.2, 3.1, 2.9]
Modified measurements: [0.8, 1.2, 3.1, 4.8, 2.9]
Removed value: 5.2
Length: 5
Maximum: 23.0
Minimum: 19.8
Sum: 106.7
Average: 21.34

A.6.2 Dictionaries

Temperature: 23.5°C
Location: Building A
Updated data: {'temperature': 24.1, 'humidity': 65, 'pressure': 1013.25, 'location': 'Building A', 'wind_speed': 5.2}
Keys: ['temperature', 'humidity', 'pressure', 'location', 'wind_speed']
Values: [24.1, 65, 1013.25, 'Building A', 5.2]

Sensor readings:
temperature: 24.1
humidity: 65
pressure: 1013.25
location: Building A
wind_speed: 5.2

Steel Properties:
density: 7850
young_modulus: 200000000000.0
yield_strength: 250000000.0
poisson_ratio: 0.3

A.6.3 Tuples

Latitude: 45.5, Longitude: -73.6
RGB: R=255, G=128, B=0

Beam Analysis:
Dimensions: 0.3m × 0.5m × 12.0m
Cross-sectional area: 0.15 m²
Volume: 1.7999999999999998 m³

A.7 NumPy Fundamentals

A.7.1 Introduction to NumPy

NumPy is the foundation for scientific computing in Python. It provides efficient arrays and mathematical functions.

1D array: [1.2 2.5 3.1 4.8 2.9]
2D array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Array shape: (5,)
Array size: 5
Data type: float64
2D array shape: (3, 3)

A.7.2 Creating Arrays

Zeros: [0. 0. 0. 0. 0.]
Ones:
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
Identity:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
Range: [0 2 4 6 8]
Linspace: [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
Random: [0.70057893 0.75695514 0.77375565 0.15431653 0.62415934]

Time array shape: (101,)
Signal array shape: (101,)
First 5 time points: [0.  0.1 0.2 0.3 0.4]
First 5 signal values: [ 0.          4.75528258  2.93892626 -2.93892626 -4.75528258]

A.7.3 Array Operations

Data 1: [1 2 3 4 5]
Data 2: [ 2  4  6  8 10]
Addition: [ 3  6  9 12 15]
Multiplication: [ 2  8 18 32 50]
Power: [ 1  4  9 16 25]
Division: [2. 2. 2. 2. 2.]

Angles (degrees): [ 0 30 45 60 90]
Sin values: [0.         0.5        0.70710678 0.8660254  1.        ]
Cos values: [1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]

Measurements: [12.1 11.8 12.3 11.9 12.  12.2 11.7]
Mean: 12.00
Standard deviation: 0.200
Maximum: 12.3
Minimum: 11.7

A.7.4 Array Indexing and Slicing

Full array: [ 10  20  30  40  50  60  70  80  90 100]
First element: 10
Last element: 100
First 5 elements: [10 20 30 40 50]
Last 3 elements: [ 80  90 100]
Every second element: [10 30 50 70 90]

Matrix:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Element at row 1, column 2: 7
First row: [1 2 3 4]
Second column: [ 2  6 10]
Submatrix (first 2 rows, last 2 columns):
[[3 4]
 [7 8]]

Measurements: [1.2 2.5 3.1 4.8 2.9 5.2 1.8]
Values > 3.0: [3.1 4.8 5.2]
Pressure readings: [1013 1015 1009 1020 1025  995 1018]
Normal pressure readings: [1013 1015 1009 1020 1018]

A.7.5 Array Reshaping and Manipulation

1D array: [ 0  1  2  3  4  5  6  7  8  9 10 11]
2D array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
3D array:
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]

Original matrix:
[[1 2 3]
 [4 5 6]]
Transposed matrix:
[[1 4]
 [2 5]
 [3 6]]

Array 1: [1 2 3]
Array 2: [4 5 6]
Concatenated: [1 2 3 4 5 6]
Vertical stack:
[[1 2 3]
 [4 5 6]]
Horizontal stack: [1 2 3 4 5 6]

A.8 Matplotlib Basics

A.8.1 Introduction to Matplotlib

Matplotlib is Python’s primary plotting library. We’ll use the pyplot interface, which provides MATLAB-like plotting commands.

<Figure size 800x600 with 1 Axes>

A.8.2 Line Plots

<Figure size 1000x600 with 1 Axes>
<Figure size 1200x800 with 3 Axes>

A.8.3 Scatter Plots

<Figure size 800x600 with 1 Axes>
<Figure size 1000x600 with 1 Axes>

A.8.4 Bar Charts

<Figure size 1000x600 with 1 Axes>
<Figure size 1000x600 with 1 Axes>

A.8.5 Histograms

<Figure size 1000x600 with 1 Axes>
<Figure size 1200x500 with 2 Axes>

A.8.6 Subplots and Figure Layout

<Figure size 1200x1000 with 4 Axes>

A.8.7 Customizing Plots

<Figure size 1200x800 with 1 Axes>

A.9 File Input/Output

A.9.1 Reading and Writing Text Files

Data written to file successfully!
File content:
Sensor,Temperature,Humidity,Pressure
Sensor_A,23.5,65,1013.2
Sensor_B,24.1,62,1014.8
Sensor_C,22.8,68,1012.5
Sensor_D,25.0,60,1015.1

Reading line by line:
Line 1: Sensor,Temperature,Humidity,Pressure
Line 2: Sensor_A,23.5,65,1013.2
Line 3: Sensor_B,24.1,62,1014.8
Line 4: Sensor_C,22.8,68,1012.5
Line 5: Sensor_D,25.0,60,1015.1

A.9.2 Working with CSV Files

CSV file created successfully!
Headers: ['Time', 'Temperature', 'Pressure', 'Humidity']

Data rows:
['00:00', '23.5', '1013.2', '65']
['01:00', '24.1', '1014.8', '62']
['02:00', '22.8', '1012.5', '68']
['03:00', '25.0', '1015.1', '60']

Using DictReader:
Time: 00:00, Temperature: 23.5°C
Time: 01:00, Temperature: 24.1°C
Time: 02:00, Temperature: 22.8°C
Time: 03:00, Temperature: 25.0°C

A.9.3 NumPy File Operations

NumPy array saved as binary file!
NumPy array saved as text file!
Loaded binary data shape: (100,)
Loaded text data shape: (100, 2)
First 5 binary values: [0.07783611 0.53778936 0.87308235 0.94466337 0.5500414 ]
First 5 text rows:
[[0.       0.077836]
 [0.10101  0.537789]
 [0.20202  0.873082]
 [0.30303  0.944663]
 [0.40404  0.550041]]

A.10 Error Handling

A.10.1 Try-Except Blocks

5.0
Error: Cannot divide by zero!
None
Error: Invalid data types for division!
None
Stress: 100000.0 Pa
Value Error: Area must be positive
Stress: None
Error: Force and area must be numbers
Stress: None

A.10.2 File Handling with Error Management

Output
Warning: Error processing line 2: list index out of range
Warning: Error processing line 3: list index out of range
Warning: Error processing line 4: list index out of range
Warning: Error processing line 5: list index out of range
Warning: Error processing line 6: list index out of range
Warning: Error processing line 7: list index out of range
Warning: Error processing line 8: list index out of range
Warning: Error processing line 9: list index out of range
Warning: Error processing line 10: list index out of range
Warning: Error processing line 11: list index out of range
Warning: Error processing line 12: list index out of range
Warning: Error processing line 13: list index out of range
Warning: Error processing line 14: list index out of range
Warning: Error processing line 15: list index out of range
Warning: Error processing line 16: list index out of range
Warning: Error processing line 17: list index out of range
Warning: Error processing line 18: list index out of range
Warning: Error processing line 19: list index out of range
Warning: Error processing line 20: list index out of range
Warning: Error processing line 21: list index out of range
Warning: Error processing line 22: list index out of range
Warning: Error processing line 23: list index out of range
Warning: Error processing line 24: list index out of range
Warning: Error processing line 25: list index out of range
Warning: Error processing line 26: list index out of range
Warning: Error processing line 27: list index out of range
Warning: Error processing line 28: list index out of range
Warning: Error processing line 29: list index out of range
Warning: Error processing line 30: list index out of range
Warning: Error processing line 31: list index out of range
Warning: Error processing line 32: list index out of range
Warning: Error processing line 33: list index out of range
Warning: Error processing line 34: list index out of range
Warning: Error processing line 35: list index out of range
Warning: Error processing line 36: list index out of range
Warning: Error processing line 37: list index out of range
Warning: Error processing line 38: list index out of range
Warning: Error processing line 39: list index out of range
Warning: Error processing line 40: list index out of range
Warning: Error processing line 41: list index out of range
Warning: Error processing line 42: list index out of range
Warning: Error processing line 43: list index out of range
Warning: Error processing line 44: list index out of range
Warning: Error processing line 45: list index out of range
Warning: Error processing line 46: list index out of range
Warning: Error processing line 47: list index out of range
Warning: Error processing line 48: list index out of range
Warning: Error processing line 49: list index out of range
Warning: Error processing line 50: list index out of range
Warning: Error processing line 51: list index out of range
Warning: Error processing line 52: list index out of range
Warning: Error processing line 53: list index out of range
Warning: Error processing line 54: list index out of range
Warning: Error processing line 55: list index out of range
Warning: Error processing line 56: list index out of range
Warning: Error processing line 57: list index out of range
Warning: Error processing line 58: list index out of range
Warning: Error processing line 59: list index out of range
Warning: Error processing line 60: list index out of range
Warning: Error processing line 61: list index out of range
Warning: Error processing line 62: list index out of range
Warning: Error processing line 63: list index out of range
Warning: Error processing line 64: list index out of range
Warning: Error processing line 65: list index out of range
Warning: Error processing line 66: list index out of range
Warning: Error processing line 67: list index out of range
Warning: Error processing line 68: list index out of range
Warning: Error processing line 69: list index out of range
Warning: Error processing line 70: list index out of range
Warning: Error processing line 71: list index out of range
Warning: Error processing line 72: list index out of range
Warning: Error processing line 73: list index out of range
Warning: Error processing line 74: list index out of range
Warning: Error processing line 75: list index out of range
Warning: Error processing line 76: list index out of range
Warning: Error processing line 77: list index out of range
Warning: Error processing line 78: list index out of range
Warning: Error processing line 79: list index out of range
Warning: Error processing line 80: list index out of range
Warning: Error processing line 81: list index out of range
Warning: Error processing line 82: list index out of range
Warning: Error processing line 83: list index out of range
Warning: Error processing line 84: list index out of range
Warning: Error processing line 85: list index out of range
Warning: Error processing line 86: list index out of range
Warning: Error processing line 87: list index out of range
Warning: Error processing line 88: list index out of range
Warning: Error processing line 89: list index out of range
Warning: Error processing line 90: list index out of range
Warning: Error processing line 91: list index out of range
Warning: Error processing line 92: list index out of range
Warning: Error processing line 93: list index out of range
Warning: Error processing line 94: list index out of range
Warning: Error processing line 95: list index out of range
Warning: Error processing line 96: list index out of range
Warning: Error processing line 97: list index out of range
Warning: Error processing line 98: list index out of range
Warning: Error processing line 99: list index out of range
Warning: Error processing line 100: list index out of range
Warning: Error processing line 101: list index out of range
No data read

A.11 Common Engineering Patterns

A.11.1 Data Processing Pipeline

Original data: 100 points
After outlier removal: 99 points
Data smoothed with moving average
<Figure size 1200x600 with 2 Axes>

A.11.2 Simple Statistics Calculator

==================================================
STATISTICAL ANALYSIS REPORT
==================================================
Sample size: 10
Mean: 12.0100
Standard deviation: 0.2601
Minimum: 11.6000
Maximum: 12.4000
Range: 0.8000
Coefficient of variation: 2.17%
95% Confidence interval: [11.8239, 12.1961]
==================================================

A.11.3 Unit Converter

Length conversions:
2.5 m = 8.20 ft = 98.4 in

Pressure conversions:
250 MPa = 36258 psi = 2500 bar

A.12 Best Practices and Tips

A.12.1 Code Organization

First natural frequency: 20.38 Hz

A.12.2 Debugging Tips

DEBUG: Input force = 10000 N
DEBUG: Input area = 0.01 m²
DEBUG: Calculated stress = 1000000.0 Pa = 1.00 MPa
DEBUG: Material yield strength = 250.0 MPa
DEBUG: Actual safety factor = 250.00
DEBUG: Is safe? True

Final result: {'stress': 1000000.0, 'safety_factor': 250.0, 'is_safe': True}

A.12.3 Performance Tips

Python loop time: 0.0130 seconds
NumPy time: 0.0017 seconds
NumPy is 7.9x faster!

Array building comparison for 10000 elements:
Method 1: List append + convert
Method 2: Preallocated array
Method 3: Vectorized operation (fastest)

A.13 Summary and Next Steps

Key Concepts Covered

You’ve learned the essential Python programming concepts needed for engineering applications:

  1. Variables and Data Types: Numbers, strings, booleans

  2. Control Structures: if/else, for loops, while loops

  3. Functions: Creating reusable code blocks

  4. Data Structures: Lists, dictionaries, tuples

  5. NumPy: Efficient numerical arrays and operations

  6. Matplotlib: Data visualization and plotting

  7. File I/O: Reading and writing data files

  8. Error Handling: Managing and preventing errors

  9. Engineering Patterns: Common code structures for engineering problems

Practice Exercises

To reinforce your learning, try these exercises:

  1. Practice basic syntax with simple calculations

  2. Work with real engineering data using NumPy and Matplotlib

  3. Learn additional libraries:

    • SciPy: Advanced scientific computing

    • Pandas: Data manipulation and analysis

    • SymPy: Symbolic mathematics

  4. Apply to your field: Use Python for your specific engineering problems

Resources for Continued Learning

Remember: The best way to learn programming is by doing. Start with simple problems and gradually work up to more complex engineering applications!


This concludes Appendix A: Python Programming Essentials for Engineers. You now have the foundation needed to tackle the advanced topics in the main course chapters.