Introduction to Python for Engineers

Python is a high-level and general-purpose programming language. According to several survey results or search engine queries such as the TIOBE index, it is one of most popular programming languages. Part of the reason that it is a popular choice for scientists and engineers is the language versatility, online community of users, and powerful analysis packages such as Numpy and Scipy.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
import datetime as datetime
from datetime import timedelta
from plotly.subplots import make_subplots

#pip install bar_chart_race
import bar_chart_race as bcr

url = 'http://apmonitor.com/che263/uploads/Main/'
data = pd.read_csv(url+'programming_languages.csv')
data['Date'] = pd.to_datetime(data['Date']).dt.strftime('%Y-%m')

df=data.copy()
df.index=df['Date'].tolist()
df=df.drop('Date',axis=1)

def make_bcr(df):
    bcr.bar_chart_race(
        df=df,
        filename='programming_languages.mp4',
        orientation='h',
        sort='desc',
        n_bars=20,
        fixed_order=False,
        fixed_max=False,
        steps_per_period=6,#speed control
        interpolate_period=False,
        label_bars=True,
        bar_size=.95,
        period_label={'x': .99, 'y': .25, 'ha': 'right', 'va': 'center'},
        #period_fmt='%B %d, %Y',
        period_summary_func=lambda v, r: {'x': .99, 'y': .18,'s': '',
                                          'ha': 'right', 'size': 8,
                                          'family': 'Courier New'},
        period_length=400,
        figsize=(5,3),
        dpi=500,
        cmap='dark24',
        title='Programming Language Popularity',
        title_size=10,
        bar_label_size=7,
        tick_label_size=5,
        shared_fontdict={'color' : '.1'},
        scale='linear',
        writer=None,
        fig=None,
        bar_kwargs={'alpha': .7},
        filter_column_colors=True)

make_bcr(df)

There are several resources for learning Python online. For a good start, look at Code Academy (Python track) or view the documentation at Python.org. For users with a foundation in MATLAB, there are excellent resources that demonstrate equivalent Python (Numpy) commands.

Install Python on Windows

Install Python on MacOS

Install Python on Linux

Online Platforms

There are several online platforms that allow Python through a web-browser including Try Jupyter and Google Colab.

Install Packages with pip (Command Line)

Sometimes a script uses a package that is not yet installed. Once Python is installed, a package manager such as pip or conda can be used to install, remove, or update packages.

Below is an example on how to install GEKKO Optimization Suite from the command line (start cmd).

 pip install gekko

The GEKKO package name can be replaced with any available package name such as NumPy.

 pip install numpy

Install Packages with pip (Python Script)

Packages can also be managed from a Python script by attempting to load the package with try. If the import fails, the except section imports pip and installs the package.

Load and Optionally Install GEKKO Package

module='gekko'
try:
    from pip import main as pipmain
except:
    from pip._internal import main as pipmain
pipmain(['install',module])

Load and Optionally Install NumPy Package

module='numpy'
try:
    from pip import main as pipmain
except:
    from pip._internal import main as pipmain
pipmain(['install',module])

The GEKKO or NumPy package names can be replaced with any available package. The pip package manager connects to an online repository to retrieve the latest version of the package and install it. Sometimes a package is needed on a computer that isn't connected to the internet or the package isn't available through pip. Below is information on installing a package wheel (whl) file.

Install Package Wheels (whl) Offline

The pip package manager can also be used to install local (previously downloaded) wheel (.whl) files but dependencies may not be automatically installed if not connected to the internet. Below is an example wheel file installation for NumPy version 1.13.1 and SciPy version 0.19.1 for Python 3.6 with 64-bit Python.

 pip install numpy-1.13.1+mkl-cp36-cp36m-win_amd64.whl
 pip install scipy-0.19.1-cp36-cp36m-win_amd64.whl

Non-Ideal Gas Equation

This same tutorial is also show in a MATLAB introduction.

Source Code

R = 0.0821  # L-atm/K
T = 500     # K
V = 5       # L/mol
Pc = 37.2   # atm
Tc = 132.5  # K

a = 0.427 * pow(R,2) * pow(Tc,2.5) / Pc
b = 0.0866 * R * Tc / Pc

# Compute in atm
P_ig = R * T / V
P_rk = R * T / (V-b) - a/(V*(V+b)*pow(T,0.5))

# Convert to Pascals
P_ig = P_ig * 101325
P_rk = P_rk * 101325

print("The ideal gas pressure: " + str(P_ig) + " Pa")
print("The Redlich-Kwong pressure: " + str(P_rk) + " Pa")

Generative AI Learning

The Python half of the course begins here. For the next three classes (introduction, functions and conditionals, arrays and loops) write every line of code yourself - the AI is your quizmaster and adversary, not your code generator. Fluency you build now is what lets you audit AI-generated code later in the course.

"Quiz me with 5 questions, one at a time, on getting started with Python: what the difference is between Python (the interpreter), a script, and a package, what pip does and how to install a package like numpy from the command line or a Jupyter cell, what an import statement makes available, why 5/2 and 5//2 give different answers, and what a variable actually stores. Grade my answers and list my misconceptions."
"I typed the Redlich-Kwong / ideal gas example from this page myself. Without giving me code, ask me 4 questions, one at a time, that check I understand what it does: what each constant is and its units, why the two pressures differ and which is more physical at these conditions, what would change at low pressure, and what error message I would get if I forgot to import numpy. Grade my answers."

Tip: If you have not yet, complete Part 2 of Engineering Computing with AI Assistants this week - it sets up your Python + AI toolchain and the verification habits used in the rest of the course.

What to Turn In

Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but the code and the checks must be your own. Answer these questions:

  1. Include evidence your installation works: a pip list screenshot (or Colab equivalent) showing numpy, scipy, matplotlib, and pandas, plus the output of one script you typed and ran yourself.
  2. Run the non-ideal gas example: report the ideal and Redlich-Kwong pressures at the given temperature and volume, and explain in 2-3 sentences why they differ and which you would report to a client.
  3. Change one condition (temperature or volume) and predict the direction of the change in both pressures BEFORE running. Was your prediction right?
  4. From the quiz prompt: one question you missed and the corrected answer.

Course Information

Excel and VBA

Python

MATLAB

MathCAD

Related Courses

Admin