PCI Geomatics -

# Overview

This tutorial provides an introduction to Python. Additional information about Python, including complete lists of built-in functions, data types and operators can be found at # Prerequisites

• Geomatica 2015 or later installed

# Tutorial

Before beginning to script in Python for Geomatica, there are basic concepts that must be understood. Similar to any programming language Python has specific syntax. Indentation is important in Python and indicates when a certain line in the script will be run. When scripting in python you will likely use an IDE. If you are not yet using a specific IDE you can complete this tutorial using IDLE which comes with the python install Start > All Programs > Python 2.7 > IDLE (Python GUI). When the shell opens choose File > New Window. Save your new file with a .py extension (e.g. PythonIntro.py). You can create and run your scripts using this IDE.

## Data Types and Operators

Python includes the following data types that can be used within a script:

 Data Type Description Example Boolean True or False value that is produced from a certain operation. Integer Whole number which can be positive or negative. - ∞ to ∞ 5, -25, 2000, -124 Float Any number, including numbers with decimals. 1.2565, -10.597 String Collection of numbers or characters. “Hello”, “175 Broadway Ave” List A non-fixed number of elements in a collection. You can add (append) or remove elements from a list after it is defined. [1, 2, 3, 4] Tuple A fixed number of elements in a collection. You cannot add or remove values from a tuple after it is defined. (1, 2, 3, 4)

These data types are used when defining variables in Python. Variables are defined in code to keep certain values in “memory”. These values can be called upon later by using the variable name. To practice defining variables and viewing the outcome of operations, open the Python command line (Start > All Programs > Python 2.7 > Python (command line)) or use the Python 2.7.5 Shell that opens with IDLE.

1. In the Python Shell enter A=25 and hit enter. You have just defined the variable A as 25. 2. Now type B=50 and hit enter. You have now defined two variables. 3. You can now add these two variables using the + Enter A+B and hit enter. There are various operators that can be used in Python scripts:

 Operator Description Example + Add two values 4+2 gives you 6 “Hello” + “ World” gives you “Hello World” - Subtract two numbers 4-2 gives you 2 * Multiply two numbers 4*2 gives you 8 ** Determines the exponential value 10**2 gives you 100 / Divide two numbers. Performs differently with two integers vs float numbers. If two integers are divided an integer with be produced. If one number is a floating number a floating number is produced. 10/3 gives you 3 10.0/3 gives you 3.3333 // Divides two numbers but will not display the decimal value 10.0//3 gives you 3.0 % Remainder of two numbers 10%3 gives you 1 = States that the value of the right side is assigned to the left side variable A= 1+2 The variable A is now set to 3 == Compares two variables. A Boolean value is produced 1==1 gives you True # Signifies that the line of code is a comment. Comments are added to code to allow the reader to understand the purpose of the code. # This is a comment and is not executed by Python print Prints the value of what follows print 5 will give you 5 print 5+5 will give you 10

## Lists

Once the basics of Python are understood, more complicated scripts can be written. Understanding how lists work is important for creating scripts.

1. In the Python Shell create a variable assignment: List1= [1, 2, 3, “a”, “b”, “happy”]. Lists are numbered starting at 0. In this example 1 is the 0th value, 2 is the 1st value and so on. 2. You can extract specific values from the list using List1 [value]. Ranges of values can also be extracted using List1[n:m]. When ranges are used list items are extracted, starting at the nth item and continuing up to but not including the mth The range [2:4] will produce the 2nd and 3rd list items. 3. Add a value to the end of the list with append(5). A 5 is added to the end of the list. ## Conditional Statements

An important part of scripting is working with conditional statements and loops. An if statement is an example of a conditional statement. An if statement makes use of Boolean values to redirect the program to a specific part of the script.

1. In IDLE choose File > New to create a new Python File. Type in the example below. The type() function produces the data type of var1. If the data type of var1 is a string, the if statement is true and the first line “Variable one is a string” will be printed. If var1 is not a string, the if statement is false the else line “Variable one is not a string” will be printed. Note that the print statements are indented which means that they are part of the if or else statements.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13``` ```# Define Variables letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] var1 = 'Hello' var2 = 'fun' # This if statement determines whether the input is a string if type(var1) is str: print 'Variable one is a string' else: print 'Variable one is not a string' ```

2. Save this file into a directory and name it WorkingInPython.py.

3. Run the script. In IDLE choose Run > Run Module The result of the script will then appear in the Python Shell 4. You can also run this file through the command prompt. Open your command prompt window (Start > type cmd).

5. Navigate to the directory where you stored WorkingInPython.py. 6. Click enter and on the next line type python WorkingInPython.py. The line “Variable one is a string” will appear. The script was executed, the if statement determined the variable type and chose the first option. If you change var1 to a number and run the script again the line “Variable one is not a string” will appear. ## For Loops

In the example below, the for statement iterates through each item in the list and adds one to the count variable. It then prints out the count variable. Once all of the items in the list have been iterated through the program exits the loop.

1. Add the for loop below to your file. Again you will notice that the count and print lines are tabbed. This means that they are executed within the loop. For each value in letters the count and print lines are executed.

2. You will also notice that the operator += was used to increase the variable count by 1. Using this operator does the same job as using count = count + 1. The count variable is loaded, one is added and then it is saved back to the variable count.

 ```16 17 18 19 20 21``` ```# This for statement iterates through all values in the list 'letters' # and prints out the total number of values within the list count = 0 for i in letters: count += 1 print count ```

3. Run the file as you did with the if statement above and observe the output of the loop. ## While Loops

Another type of loop is a while loop. A while loop examines a statement. While the statement is true the loop will cycle. If the statement becomes false the loop will end. In the example below the loop continues until the length of the new list1 is no longer less than 4. On each iteration, the nth value of letter is appended to list1. Each time the count increases, the next value in letter is added to list1. When all four values are added to list1, the list becomes longer than length 4 and the loop is exited. Once the loop is exited the program prints list1.

 ```24 25 26 27 28 29 30 31``` ```# This while loop takes all the values from the list 'letters' # and appends them to the empty 'list1' count = 0 list1 = [] while len(list1) < 4: list1.append(letters[count]) count += 1 print list1 ```

## Functions

In Python, functions are sections of code which take in arguments, perform a task and output information. Functions are often added into scripts to minimize the amount of coding. For example, if in your script you want to constantly perform a series of math problems and produce the final result you can create a function. Therefore every time you need to perform those math problems, you can call on the function you defined. The example below takes in three values, performs a math equation with those values and then produces the final result.

You can also define your own functions in Python. Functions must always begin with def function_name (arguments): In the example below the function math has been defined. The arguments for math are x, y and z. When you want to run this function later within the script you have to give math three values. The math function executes four different math problems and then prints out the final result.

In the example below A, B and C are variables with the values 5, 2 and 7 respectively. When math(A, B, C) is called later in the script, these three values are used for the arguments x, y and z in the function.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17``` ```# Define the number variables to be used in the math expression A = 5 B = 2 C = 7 # Define the mathematical expression as the function math. This defined function can be called upon later in the script def math(x, y, z): add = x + y mult = add * z exp = mult ** z finalresult = exp / add print finalresult # Run the math function that you created. Keep in mind that 'math' always needs 3 input variables math(A, B, C) ```

When you run this script, each line of the function math is executed using these values from A, B, C and then the final result is printed. In addition to defining your own functions, you can also use built-in functions. These work the same way as user-defined functions but you do not have to include the extra definition code in your script. Here are three examples of built-in functions: 