54.4 Python Example with Logical Syntax

A primary reason for using Python in a model is to allow you to introduce logical syntax into your model, including if/then and loop syntax. The Special Features tutorial example model Python Example – Loop.trex is a simple illustration of logical syntax within a Python function.

Consider the following elements of the Python function

  • The Python function expects a numeric argument called resample_sw. A single argument must therefore be provided within parentheses whenever the Python function is called within the model.

  • The function includes a for loop to repeat a code block multiple times. The syntax for dist_index in range(1,5): designates that the loop should be repeated 4 times with dist_index values 1, 2, 3, 4 (1 at start is inclusive, 5 at end is exclusive, so 5 is not run). The indented code block is then executed 4 times, once for each iteration in the loop.

  • Similarly, if/then/else logic syntax with its own indented code.

  • Python treeage.debug statement reports information back to the TreeAge Pro Calculation trace console.

  • The return statement passes the calculated value back to the model wherever the Python function is called.

Roll back the model and the Calculation Trace Console will show the "for loop" cycling through distributions 1 to 4 and then adding them ( sum = sum + dist_sample ) before returning the value for Strategy 1 (resample_sw = 0) and Strategy 2 (resample_sw=1).

Note:In the Python function declaration, arguments are separated by commas; however, when calling the function within TreeAge Pro, those arguments are separated by semicolons.