This is the first in a series about using the Python programming language in a mechanical engineering setting. In this installment, we will look at the basics of the language and how to install Python and run programs. This article and series will be primarily for Windows since that is what most regular users and engineers will use.

Why Python?

There are numerous programming languages out there and many such ones for scientific programming. These include C/C++, Matlab, FORTRAN, R, and others. Why Python then? Well, the two main advantages to the engineer are 1) readability of code, and 2) versatility.

Python has a very readable syntax. Its syntax is based on indentation instead of delimiters such as semi-colons and curly braces. This results in much more readable code. It also has very minimal overhead – all you need is a text editor and a version of Python installed.

Because Python is a general purpose programming language, it can be used in a variety of applications. It comes with a standard library that is itself extensive. But, it can also be extended to do even more things. There are a great many packages written by others that allow for much more functionality – PyPi is Python’s own place to host these packages, at https://pypi.org/. This gives the user great versatility in developing programs. This is where I believe it shines when compared to more specific languages such as Matlab or R. (For example, packages exist that allow for the manipulation of Excel files – something that would more traditionally be done with Visual Basic.) The main benefit here is that many things can be done with a single language, which allows the engineer to not have to learn anything else – being a supplementary tool to engineering work, this is a big advantage.

Installation And Interpreter Access

Python can be installed either globally using the standard Python installer from python.org or as part of separate, bundled packages. The Python interpreter allows commands to be entered and a result returned.

Python.org

To download and install Python this way visit python.org and click on the appropriate download link:

With this method, Python is registered with the system and is available through the command line/Run utility:

Packaged Installers

The other option for installation is using a packaged distribution. Since Python is open source, others have integrated Python with additional programs such as integrated development environments (IDE’s) in order to simplify installation and setup and enhance workflows. Popular options for engineers in this route include WinPython, Pyzo, and Anaconda. Each of these includes one or more IDE’s and a Python installation along with either a set of pre-installed packages or a package manager to easily obtain more packages at a later time.

This is generally the preferred route for scientific work, since most all of the time you will need at least some additional packages – plotting, math libraries, etc. – and this will save you the effort of having to install them. For example, WinPython comes preinstalled with numerous packages.

With WinPython, a copy of Python is included here:

IDLE

The official Python distribution includes an editor called IDLE (integrated development and learning environment). This is a simple way to use the Python interpreter and run script files. It is available from the Start menu or the desktop if a shortcut was place there.

In WinPython, IDLE (along with a few other IDE’s) is included in the main installation directory:

Spyder IDE

WinPython also comes with the Spyder IDE – a Python development program geared for scientific uses. This can be launched from the top level WinPython directory. This editor features a text editor, Python consoles including the IPython workbook (an improved interpreter), and additional features such as an integrated file explorer and workspace (variable) editor.

Pyzo IDE

Some more recent versions of WinPython also include the Pyzo development environment, which offers some of the same features as Spyder but is overall more minimal. This is also located in the WinPython main directory.

Adding a Custom Windows Path

If Python is installed using a packaged program such as WinPython, Python will not be found when typing python at a command prompt because it was not registered with the system. But Windows can be told to look in a different location for the Python executable. This can be accomplished by modifying the PATH environment variable. To do this:

1) Open the Advanced System Settings under the System location in Control Panel (press Windows + Pause Break to open System settings)

2) Click on Environment Variables under the Advanced tab

3) Select the PATH variable and click Edit

4) Click on New to add a new path to search, including the directory containing the Python executable. With my installation of WinPython, the path is C:\Users\<user>\WPy-3702\python-3.7.0.amd64.

Once this path is added to the PATH variable, Python will be recognized from the command line as with a traditional system-wide Python installation.

A Brief Python Tutorial

Calculator

The Python Interpreter can be used as a basic calculator. The standard operator symbols (+-/*) found on the keyboard (and used in Excel for example) are the same in Python, with the exception of the power operator which is two asterisks **.

>>> 5+4
9
>>> 4*(2+9-54/3)
-28.0
>>> 8**2
64

Syntax

The basic feature regarding syntax in Python is indenting. In most languages parentheses and curly braces are used to separate regions of code. In Python, line breaks and indentation are used instead. No characters are needed at the end of a line to mark the end of a statement. (Though, a semicolon can be used to put more than one statement on the same line.) The following are statements:

>>> a = 5
>>> b = 2.5*a
>>> name = 'Joe'
>>> print(b)
12.5

For blocks of code associated with functions, loops, or classes (more below), the extents of each containing block is indicated by the level of indent. Python proper is to use 4 spaces for each indent. (Technically, any number of spaces could be used as long as it is consistent.) Pep 8 is the official guide to the Python style. The following is how a function with an inner if-statement would be composed:

Data Types

Python has a very flexible and general system of data types that make it easy for the non-programmer to use. The basic data types are:

 

Types Python type Syntax Examples Iterable Conversion Functions
Numbers integer None – just assign to an integer number.
num_bolts = 12
ID = 4
No
int()
float None – just assign to a decimal number.
dia = 7.46
No
float()
Text string Enclose in single (') or double (") quotes. Triple single or double quotes (''' or """) allows for multi-line strings.
fig_name = 'Run A Temperature vs Time'
Yes
str()
Lists list Enclose items in square brackets, separated by commas. Any data type can be used as an element, and they all don’t have to be the same.
diameters = [1.1, 2.0, 2.2, 1.0]
Yes
list()
tuple Enclose items in parentheses, separated by commas. Any data type can be used as an element, and they all don’t have to be the same.
force = (1.0, 2.9, -0.5)
Yes
tuple()
Key-value dictionary Use curly braces with key-value pairs separted by commas. Keys are strings and values can be any other type including other dictionaries.
speeds = { 'low': 5, 'medium': 10, 'high': 15 }
Yes
dict()
Booleans bool
True

or

False
is_fixed = True
No
bool()

However, because Python does not require you to pre-specify what type you are using when creating a variable, the usage of these is more automatic and is up to you to make sure types are used appropriately. In other words, when creating a variable you simply assign it a value and Python assigns it a type based on the implicit type of the data you provided.

Additionally there are other types available through the standard library (next section) worth considering, such as those in the collections module.

The Standard Library and the import Statement

Python ships with an extensive library of modules that allow for specific functionality: file I/O, math functions, web networking, etc. The entire list can be found in the Python docs (https://docs.python.org/3/library/index.html). By default none of these modules are available when Python is first started. To use them they must be imported. This is accomplished by using the import statement:

>>> import [module name]

This imports all (or all that specified by the module) of the data and functions associated with that module. For example, to import the math module:

>>> import math

Then, its properties and methods can be called using dot syntax:

>>> math.pi
3.141592653589793
>>> math.sin(30*math.pi/180)
0.49999999999999994

Looping

Looping (or iterating) is a basic and central concept in Python. In the table above, each of the data types listed says whether it can be iterated on. Iterating means you perform some action on each item in the variable. Iterable types are those that are composed of a sequence of elements, such as lists, tuples, dictionaries, but also strings. In the case of strings, each character is an element.

To loop over each element in a list, you use the for-in construct. For example, to print each element in a list:

>>> files = ['data.txt','plots.py','output.txt']
>>> for each in files:
	print(each)

	
data.txt
plots.py
output.txt
>>> 

Here, each is a keyword chosen by the user to represent the “current” item when looping (it can be anything, though “each” is common). It must correspond with the variable used in the body of the for loop.

To print a range of numbers:

>>> for i in range(5):
	print(i)

	
0
1
2
3
4

Functions

Functions are created in Python using the def keyword. A function must have a name and zero or more parameters. The return keyword is (optionally) used to return a value. Examples:

>>> def multiply(a,b):
	return a*b

>>> multiply(5,7)
35
>>> r = multiply(10,10)
>>> r
100

Functions can also have default values for the parmaters:

>>> def print_name(name="Joe"):
	print("Hello " + name)

>>> print_name("Bob")
Hello Bob
>>> print_name()
Hello Joe

Running Programs

In Windows

Running a Python program requires interpretation by the Python executable. The python command accepts flagged options and optionally a filename of a Python source file, followed by any arguments for the file. Suppose you have a program located on the Desktop called my_script.py containing the following, to print the current day:

from datetime import date

today = date.today()

year = today.year
month = today.strftime('%B')
day = today.strftime('%A')
day_num = today.strftime('%d').lstrip('0')

print('Today is {day}, {month} {day_num}, {year}.'.format(day=day, month=month, day_num=day_num, year=year))

This can be run with a shell command from the Windows command prompt:

which prints the output from the Python script. If the script completes (i.e. it is not waiting for user input), the Python instance closes and you are returned to the Windows shell.

A list of the available options on the python command can be found by issuing python -h.

When running programs this way you are limited to text-based output (though files such as figures could be saved to disk). Additionally, when the script finished you lose the Python variables and so it is less easy to inspect and interrogate your program. One of the advantages to using an IDE such as Spyder is that the built-in IPython console (mentioned above) has the ability to show images or figures generated by the program inline to the output console.

Within an IDE

When editing and running programs, running programs is much simpler. Each of Spyder and Pyzo has a Run command. This is also true for IDLE.