The use of Python for programming requires an introduction to a number of concepts that are either unique to Python, but required, or common programming concepts that will be invoked repeatedly when creating scripts. The following are a number of these concepts which must be covered to be fluent in Python.
Other important concepts
Indentation
Python, unlike most other programming languages, enforces strict rules on indenting lines of code. This concept derives again from Guido's desire to produce clean, readable code. When creating functions, or using for loops or if...else statements, indentation is required on the succeeding lines of code. If a for loop is included inside an if...else statement, there will be two levels of indentation. New programmers generally find it to be helpful, as it makes it easy to organize code. A lot of programmers new to Python will create an indentation error at some point, so make sure to pay attention to the indentation levels.
Functions
Functions are used to take code that is repeated over and over within a script, or across scripts, and make formal tools out of them. Using the keyword def, short for "define function", functions are created with defined inputs and outputs (which are returned from the function using the keyword return). The idea of a function in computing is that it takes in data in one state, and converts it into data in another state, without affecting any other part of the script. This can be very valuable for automating a GIS analysis.
Here is an example of a function that returns the square of any number supplied:
def square(inVal):
return inVal ** 2
>>> square(3)
9
Keywords
There are a number of keywords built into Python that should be avoided when naming variables. These include max, min, sum, return, list, tuple, def, del, from, not, in, as, if, else, elif, or, and while among many others. Using these keywords as variables can result in errors in your code.
Namespaces
Namespaces are a logical way to organize variable names, to allow a variable inside a function or an imported module to share the same name as a variable in the main script body, without overwriting the variable. Referred to as "local" variables versus "global" variables, local variables are contained within a function (either in the script or within an imported module), while global variables are within the main body of the script.
These issues often arise when a variable within an imported module unexpectedly has the same name of a variable in the script, and the interpreter has to use namespace rules to decide between the two variables.