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.

Lab1: Introduction to Python

Introduction:

Python is a powerful programming language that has become a standard tool in machine learning, data science, and scientific computing. With excellent libraries like NumPy, SciPy, and Matplotlib, Python is ideal for engineering applications. In this course, we will explore how to use Python for simulating and controlling robotic systems.

If your experience is mainly with Arduino or MATLAB, don’t worry—many concepts will feel familiar, and Python’s syntax is straightforward and beginner-friendly. With the support of modern tools and resources such as AI-assisted coding (e.g., Copilot), you’ll find that learning Python is both accessible and rewarding. Every mechanical engineer can become a confident Python coder!

This lab will only provide the basics for Python. You can try to find other resources online to learn more. For instance, this webpage provide more examples in the context of numerical methods: https://numericalmethodssullivan.github.io/ch-python.html Here is a more thorough tutorial from Python https://docs.python.org/3/tutorial/index.html

Learning Objectives:

  • Learn the structures of data and commands in Python with NumPy

  • Gain knowledge and familiarity with Jupyter notebooks and Python scientific libraries

  • Learn how to get help with Python and its libraries

  • Solve mathematical problems with Python and plot the solutions

  • Work with arrays, functions, and visualization tools

Setting Up: Selecting the Python Kernel

Before running any code in this notebook, you must select the correct Python environment (called a kernel). We have used miniconda to a dedicated environment named me416 that has all the required packages pre-installed.

Steps to select the kernel in VS Code

  1. Look at the top-right corner of the VS Code window. You will see a button showing the current kernel (it may say “Select Kernel”).

  2. Click that button. A drop-down menu will appear at the top of the screen.

  3. Choose “Python Environments...” from the menu.

  4. Select me416 from the list of available environments.

Note: If you do not see me416 in the list, please make sure you have created the environment by following the instructions in Lab0. Do not use any other kernel, as required packages may be missing.

Once the kernel is set, the top-right button should display me416. You are now ready to run the cells below.

Task 1 – Basic Python Syntax

Before diving into NumPy and scientific computing, review a few core Python syntax concepts. Python is widely used in engineering because its syntax is simple, readable, and efficient for technical work.

Key Python Concepts

  • Variables and Data Types
    Python assigns data types automatically based on the value (e.g., int, float, str, bool, complex). You do not need to declare a type before using a variable.

  • Lists and Dictionaries

    • Lists store ordered, editable collections of values.

    • Dictionaries store data as key–value pairs, which is useful for material properties and structured engineering parameters.

  • Control Flow
    if/elif/else statements let code make decisions, while for and while loops repeat tasks. These are essential for automating calculations and processing datasets.

  • Functions
    Functions package reusable logic into named blocks. This makes code cleaner, easier to test, and easier to maintain in larger engineering scripts.

  • String Formatting (f-strings)
    F-strings (for example, f"Value: {variable}") make printed output clear and concise, which helps with debugging and reporting results.

Run the code cells below using the Run button on the left side of each cell.
If this is your first run, Jupyter may ask to install ipykernel—approve the installation.

Integer: 50, type: <class 'int'>
Float: 3.14159, type: <class 'float'>
Complex: (3+4j), type: <class 'complex'>
String: MECH 416 Introduction to Robotic Manipulators, type: <class 'str'>
Boolean: True, type: <class 'bool'>
Forces: [100, 250, 75, 500]
Second force: 250 N
Last force: 500 N
After adding 150 N: [100, 250, 75, 500, 150]
First three forces: [100, 250, 75]
All forces: [100, 250, 75, 500, 150] or [100, 250, 75, 500, 150]
Material Properties:
  Steel: ρ = 7850 kg/m³, σy = 250 MPa
  Aluminum: ρ = 2700 kg/m³, σy = 70 MPa
  Titanium: ρ = 4500 kg/m³, σy = 880 MPa
✓ Force exactly at limit: 400 N
For loop example - analyzing different loads:
  Load 1: 100 N - SAFE
  Load 2: 250 N - SAFE
  Load 3: 75 N - SAFE
  Load 4: 450 N - OVER LIMIT
  Load 5: 200 N - SAFE

While loop example - finding critical load:
  Testing load: 100 N
  Testing load: 150 N
  Testing load: 200 N
  Testing load: 250 N
  Testing load: 300 N
  Testing load: 350 N
  Testing load: 400 N
  Critical load exceeded at: 450 N
Engineering Analysis:
  Applied force: 10000 N
  Cross-sectional area: 314.2 mm²
  Calculated stress: 31.8 MPa
  Safety status: ✓ SAFE

Key Takeaways:

  • Python is readable: Code should be clear and self-documenting

  • Indentation matters: Python uses indentation instead of braces {}

  • Zero-based indexing: Arrays/lists start at index 0, not 1 (unlike MATLAB)

  • Dynamic typing: Variables can change type, but be careful in engineering calculations

  • F-strings: Use f"Value: {variable}" for modern string formatting

  • Functions: Always document with docstrings for engineering work (docstrings are multi-line string comments placed right after the function definition to describe its purpose, inputs, and outputs; this helps others understand and maintain your code)

Error Handling and Debugging

Engineers need robust code that handles unexpected situations:

Testing error handling:
10 / 2 = 5.0
Error: Cannot divide 10 by zero!
10 / 0 = None
Error: Invalid input types - need numbers, got <class 'str'> and <class 'int'>
'10' / 2 = None
Beam deflection: 0.10 mm

Task 2 – Data Structures and Basic Operations

NumPy is a fundamental Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. NumPy is widely used in scientific computing, data analysis, and engineering applications. Learn more: https://numpy.org/

Matplotlib is a powerful Python library for creating static, animated, and interactive visualizations. It is widely used for plotting data, generating figures, and customizing charts in scientific and engineering applications. Learn more: https://matplotlib.org/. Here is a link with very useful cheetsheets for Matplotlib: https://matplotlib.org/cheatsheets/

Let’s start by importing these three libraries.

Basic Mathematical Operations

You can use Python like a calculator:

-1 - 1 = -2
2^2 = 4

Creating Arrays (equivalent to MATLAB matrices)

You can save answers by assigning them to variables and create arrays:

x1: [1 2 3]
x2: [ 0.        +2.j  1.        +4.j  3.14159265+0.j -1.        +0.j]
x3: [2 4 6]
y1:
[[1 2 3]
 [4 5 6]]

y2:
[[1 2 3]
 [4 5 6]]

y3:
[[ 1.  2.  3.]
 [-4. -3.  6.]]

Matrix operations

Now let’s do some basic matrix operations. NumPy provides essential matrix operations for engineering calculations.

Key Matrix Operations:

  • Matrix multiplication: A @ B

  • Element-wise multiplication: A * B

  • Transpose: A.T

  • Inverse: np.linalg.inv(A)

  • Determinant: np.linalg.det(A)

Matrix A:
[[1 2]
 [3 4]]

Matrix B:
[[2 0]
 [1 3]]

A @ B (matrix multiplication):
[[ 4  6]
 [10 12]]

A * B (element-wise multiplication):
[[ 2  0]
 [ 3 12]]

A @ vector:
[ 5 11]

A transpose (A.T):
[[1 3]
 [2 4]]

Determinant of A: -2.00
Inverse of A:
[[-2.   1. ]
 [ 1.5 -0.5]]

Dot product of v1 and v2: 32
  v1 · v2 = (1)(4) + (2)(5) + (3)(6) = 32

Cross product of v1 and v2: [-3  6 -3]
  v1 × v2 = [-3  6 -3]

Task 3 – Built-in Functions and Plotting

Python with NumPy has many built-in functions similar to MATLAB. The general structure is: result = function_name(input1, input2, ...)

a = [4 9 7]
sqrt(a) = [2.         3.         2.64575131]
[max, min, mean] = [9.         4.         6.66666667]
Size of a: (3,)

Common Mathematical Functions

Here are some commonly used functions:

arctan(1) = 0.7853981633974483 radians = 45.0 degrees
Random number: 0.949121739404197
Random 3x3 array:
[[0.19 0.26 0.79]
 [0.62 0.46 0.09]
 [0.72 0.92 0.28]]

2D Plotting

<Figure size 1000x600 with 1 Axes>

For a DC motor, we can plot the torque-speed curve as a line if given the tau_stall and omega_nl.

τ(ω)=τstall(1−ωωnl)\tau(\omega) = \tau_{stall}\left(1-\frac{\omega}{\omega_{nl}}\right)
<Figure size 1200x500 with 2 Axes>

Plot with Custom Functions

In Python, you can define custom functions easily:

<Figure size 1000x600 with 1 Axes>

Task 4 – Debugging Techniques in Python

Effective debugging is crucial for engineering applications where accuracy is paramount. Python offers several powerful debugging tools and techniques that every engineer should know. We will mainly use the following:

EXAMPLE: Simply supported beam with two point loads

DEBUG: Analyzing beam of length 8 m
DEBUG: Loads = [500 800] N at positions = [2 5] m
DEBUG: Sum of vertical forces (total load): 1300 N
DEBUG: Sum of moments about support A: 5000 N·m
DEBUG: Coefficient matrix M:
[[1 1]
 [0 8]]
DEBUG: Right-hand side vector b: [1300 5000]
DEBUG: Determinant of M: 8.0000
DEBUG: Reaction at A: 675.00 N
DEBUG: Reaction at B: 625.00 N
DEBUG: Check - R_A + R_B = 1300.00 N (should equal total load 1300 N)

FINAL RESULT:
  Reaction at Support A: 675.0 N
  Reaction at Support B: 625.0 N

HW Problems

Now that you’ve learned the basics, practice the following problems. Work through them step by step, using the debugging techniques you’ve learned. You need to submit your solutions to these HW problems with your source code.

Problem 1: Basic Python Syntax and Control Flow

In this problem, you will analyze material properties for design selection.

Task: Write a program that:

  1. Creates a dictionary of materials with their properties (density, yield strength, cost per kg)

  2. Finds the material with the highest strength-to-weight ratio

  3. Determines which materials are suitable for a given application (yield strength > 200 MPa, cost < $10/kg)

  4. Uses proper error handling for invalid inputs

Given data:

  • Steel: density=7850 kg/m³, yield=250 MPa, cost=$2/kg

  • Aluminum: density=2700 kg/m³, yield=70 MPa, cost=$8/kg

  • Titanium: density=4500 kg/m³, yield=880 MPa, cost=$30/kg

  • Carbon Fiber: density=1600 kg/m³, yield=600 MPa, cost=$50/kg

Problem 2: NumPy Arrays and Mathematical Operations

In this problem, you will analyze experimental strain gauge data and plot them.

Task: Given strain measurements from 5 gauges over 10 time steps:

  1. Create a 2D NumPy array (10 time steps × 5 gauges) with realistic strain data

  2. Calculate the maximum, minimum, and average strain for each gauge

  3. Find the time step where the maximum overall strain occurred

  4. Calculate the stress using σ = E × ε (E = 200 GPa for steel)

  5. Plot strain vs time for all gauges on the same plot with different colors

  6. Add proper labels, legend, and title

Hints:

  • Use np.random.normal() to generate realistic strain data around 0.001 (1000 microstrain)

  • Use np.argmax() to find indices of maximum values

  • Remember to convert units properly (strain is dimensionless, stress in Pa)