Any respectable programming tutorial starts with a hello world example, so let’s get that out of the way!
If you haven’t opened the Python console yet, do it now: Plugins | Python console.
The Python console is an interactive command line interface. This means that you can type in a line of code and – once you press Enter – the code is executed.
In our hello world example, we use the print function to output the text “Hello world!” in the console. The corresponding code is:
We are calling the print function with one parameter: the text (also known as string) value “Hello world!”.
When you type this command into the Python console input field, you’ll see that it shows text in different colors. This is called syntax highlighting, and the colors make it easier to make sure that what we’re typing is correct. In addition, when typing closing brackets, it highlights the corresponding opening bracket. This is very useful, since missing brackets are a common programming mistake.
If you have seen some Python code in the past, you might have seen print statements such as print “Hello world!” without brackets. This syntax is not valid in Python 3 anymore and would cause this error: SyntaxError: Missing parentheses in call to ‘print’
After pressing Enter, you will see that our code outputs Hello world! in the console:
These are the basics of using the Python console and how to execute a function with a string parameter.
That’s enough non-GISy basics for now, let’s get our hands dirty with some spatial data!
PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!