A. Python

To perform calculations with pDynamo, users write Python scripts that employ the packages of the pDynamo library. Python is a dynamic, interactive, open-source scripting language with a very active user community. Comprehensive documentation is available on the Python web site.

The best way to learn Python is to write scripts. A simple example is as follows:

import math


# . Define a squaring function.

def Square ( x ):

return x**2


# . Create a range of integers.

values = range ( 10 )


# . Loop over the integers.

for i in values:

x = float ( i )

print ( "{:5d}{:10.5f}{:10.5f}{:10.5f}".format ( i, x, math.sqrt ( x ), Square ( x ) ) )

To run the script, the Python interpreter must be invoked. There are a number of ways to do this but one of the simplest is to open a terminal window and enter python3 on the command line. The program can then be typed in, taking care to respect the case of the characters and the number of spaces that appear at the beginning of each line. Blank lines can be omitted if desired, as can lines starting with the hash character (#) because these are comments. What happens when typing is finished? What does the program do?

Being able to type scripts directly into the Python interpreter is very useful for trying things out, but becomes tedious for more complicated tasks. In these cases, it is easiest to put the script in a text file and then invoke Python with the name of the text file as an argument. The above program appears in the file Example0.py of the pDynamo3 distribution and may be run by typing python3 Example0.py.

Exercises

    1. Experiment further with Python by writing some simple programs. A good place to start is to modify Example0.py so that other functions, such as additional powers, of the numbers are calculated.