Programming is about automation of computational tasks. For those new to programming, it can help to compare it to something more familiar, such as a recipe. A recipe usually has a list of ingredients at the top, and then some instructions about what to do with the ingredients.
To continue the recipe analogy, combining two or more recipes together may be necessary for more complex dishes, or some that just need a garnish or glaze at the end that cannot be cooked with the rest of the recipe. We give the recipe to someone else who is a master sous chef, but extremely literal, and will not correct any mistakes in a recipe. If we have planned well and tested it ourselves, we will get back exactly what we expect. If we wrote some ingredients or amounts down wrong, it may taste very strange, and if the instructions are incorrect, it may not be thoroughly cooked, or it may be burned.
To understand how this analogy applies to programming, we must learn some terms. If anyone has used Excel to add numbers, they have already done some simple programming. You put values in cells and then list those cell names together with the word “sum” with parenthesis around the cell names, and you get the result.
Variables in Python
In programming terminology, a variable is a symbolic name that points to some value. In Excel, this is the cell name, such as A1 or B5. A well-written program usually starts with the variables at the top and a list of instructions on what to do with those variables. This can seem daunting for a complex program, but we will see that it can always be broken up into smaller pieces that can be combined in the end. The same must be done with programming. The user needs to understand the process so well that they can explain it to the computer, which gives back exactly what we ask. If we do not choose the correct variables, in the beginning, the answer will be wrong. If we do not have the correct instructions, it might not come back with anything that works at all.
Watch the video for an introduction to the basics of variable creation and math functions used in Python.
If you do not have any programming experience, start out by reading through the Beginner’s Guide to Python. You will find a short explanation of what Python is in addition to links to numerous resources such as online documentation and tutorials.
Here is a sample of assigning and viewing variable values:
>>> y=”I am changed”
’I am changed’
Going through each command:
x is assigned a value of 15
y is assigned to point to the variable x
x is entered on a line, which prompts the console to print the value, which is 15
y is entered and it has the same value of 15 shown
y is assigned a string value
x is entered and still shows a value of 15
This highlights a feature of python that can be different from other programming languages. Python can easily change variable types from an integer to a string or any other object whenever they are set. It will not complain about assigning anything that actually exists in a variable name, so it can be easy to overwrite something if your variable names are vague, like single letters. Try to get in the habit of naming them something more meaningful like x_point_label or y_centroid.
Conditions in Python
Testing conditions use branching logic to perform one operation if a condition is met and another operation if that condition is not met. In Python, the if, else statement is used.
Building on the previous example, an if, else statement can be used to test the value of a variable.
|if x == 15:
print “the variable is out of range”
The following operators can be used:
== tests equality
!= is not equal to
< is less than
> is greater than
Watch the video to see conditional examples in action.
FOR and While Loop in Python
Looping can be used for code that is to run more than once. The following techniques can be used for iterating or looping:
The while statement
|x = 1
while x < 10:
x = x + 1
Counted loops using the for statement
|For num in range(1,10):
List loops using the for statement
|x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in x:
Watch the video which discusses the FOR and WHILE loops
Python uses objects to represent everything. All objects have:
- Properties that describe it
- Methods (things that an object can do)
Classes in Python
A class is used to create an object. An object has methods and properties. Classes are used for tool parameters and working with geometry.
A class may be thought of as a blueprint for creating objects. The blueprint determines what properties and methods an object of that class will have. A common analogy is that of a car factory. A car factory produces thousands of cars of the same model that are all built on the same basic blueprint. In the same way, a class produces objects that have the same predefined properties and methods.
In Python, classes are grouped together into modules. You import modules into your code to tell your program what objects you’ll be working with. You can write modules yourself, but most likely you’ll bring them in from other parties or software packages. For example, the first line of most scripts you write in this course will be:
Here you’re using the import keyword to tell your script that you’ll be working with the arcpy module, which is provided as part of ArcGIS. After importing this module, you can create objects that leverage ArcGIS in your scripts.
Inheritance in Python
Another important feature of object-oriented languages is inheritance. Classes are arranged in a hierarchical relationship such that each class inherits its properties and methods from the class above it in the hierarchy (its parent class or superclass). A class also passes along its properties and methods to the class below it (its child class or subclass). A real-world analogy involves the classification of animal species. As a species, we have many characteristics that are unique to humans. However, we also inherit many characteristics from classes higher in the class hierarchy. We have some characteristics as a result of being vertebrates. We have other characteristics as a result of being mammals. To illustrate the point, think of the ability of humans to run. Our bodies respond to our command to run not because we belong to the “human” class, but because we inherit that trait from some class higher in the class hierarchy.
Back in the programming context, the lesson to be learned is that it pays to know where a class fits into the class hierarchy. Without that piece of information, you will be unaware of all of the operations available to you. This information about inheritance can often be found in informational posters called object model diagrams.
Functions in Python
Function or subroutine in programming is a sequence of program instructions that perform a specific task, packaged as a unit. In Excel, this is the “Sum” function, which has the purpose to add all the values of the cells that are inside the parenthesis. Programming languages usually have some built-in functions to handle basic tasks, such as printing a variable. In ArcGIS, almost every toolbox has a python function that will do the same thing. Programmers can also create new or more specific functions to break up the code into easier to understand pieces.
Watch the video to learn how to combine actions into a single process that can be used later.
Module in Python
A module is a Python file where functions live. All of the functions in a module are usually related. Modules need to be imported into a Python script in order to be used.
The syntax is a series of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language. In Excel SUM function, this is that the parentheses surround the cell names that should be added. Every language has its own syntax, whether it is a programming language, or spoken language, like English. We all know that to speak clearly in English, we use a subject, a verb, and a predicate, even if we may have forgotten the exact names of these terms.
The following rules must be remembered:
- Python is case sensitive, so watch the naming convention used for variables and functions.
- Indentation is used to group together blocks of code. This is required and it adds to the readability of the code.
- Use a forward-slash as the separator for paths
- The backslash (\) is used as a line continuation character that can be used to split long statements into multiple lines for readability.