Book - 5.2) A Python programming environment
Getting Started with Python¶
To quickly build on the knowledge gained through the study of NetLogo and Blockly we will see
- how to use a Python programming environment to edit and run Python programs, and
- study the structure of a Python program using the Blockly examples.
At first, the Python code you wrote for the Blockly examples will be cut from text tab in BlockPy and pasted into the programming environment for execution. This conversion of Blockly examples to executable Python programs will make for a smooth transition into the world of Python programming. However, we will quickly reach the point where we are constructing algorithms directly in the Python language. As we progress we will see some new aspects of Python that were not seen in the Blockly examples.
A Python Programming Environment¶
We will use a freely available, multi-platform Integrated Development Environment (IDE) named Spyder for programming in Python. You will need to install on your computer Python, Spyder and possibly other elements. The class staff will help you with the download and installation. Spyder is one example of an Integrated Programming Environment (IDE), there are others for Python and for other languages as well. It is a “programming environment” because it provides the tools needed to program algorithms in Python. The tools provide a means to edit the text of the Python code, to explore the data that the program is manipulating, and interact dynamically with the executing program through the input that we provide to the program and the output that the program produces. It is “integrated” because it provides a single window in which all of the tools are simultaneously visible and because the tools can share information about the program and its execution. When you have successfully installed Spyder you will probably see the icon shown below. Clicking on this icon will launch Spyder.
The Icon to Launch the Spyder IDE
The Spyder IDE window is shown in the following figure. Spyder has three separate areas:
- the edit pane on the left where Python code can be edited
- the Variable inspector pane in the upper right where the current values associated with properties can be examined. Note: make sure that the “variable explorer” tab is selected in this pane.
- the Python console pane in the lower right where input can be entered and output is seen. Note: make sure that the “Console” tab is selected in this pane.
The Spyder IDE has many graphical controls and menus. We will learn to use the basic controls.
The Spyder IDE
Creating Code in the Edit Pane
Notice that the tab at the top of the edit pane is temp.py. To save the file use the Save As ... option in the File menu at the top of the window. The Save As dialog will ask you to choose a name for the file. You will notice that the tab “temp.py” will be changed to the name of the file you chose. In this case the file was saved as “Temp-Convert.py”. The ”.py” suffix denotes a file containing Python code.
The Python program shown in the edit pane can be executed by
- clicking the run icon (the green right pointing triangle near the top of the Spyder window) or
- select Run in the Run menu at the top of the Spyder window.
This is shown in the following figure. Notice that two entries have appeared in the Variable explorer window showing the names and value of the two properties ftemp and ctemp. Also notice that the output from the program has appeared in the Console area.
Executing Edited Code
To be a more informed user of Python and Spyder it is important to understand the relationship between the Spyder IDE and the Python interpreter as shown in the following figure. The Python interpreter is itself just a program that reads and interprets the statements in a Python program. The term interprets means that the Python interpreter is maintaining the values of properties, performing calculations, making decisions, and executing the iterations given in a Python program. The edit window specifies which Python program is being interpreted. Spyder’s Python console is used to display outputs from the program being interpreted and to accept inputs requested by the program being interpreted. Spyder’s Variable explorer interacts with the Python interpreter to display the names and current values of properties being manipulated by the Python program being interpreted.
How Spyder and the Python Interpreter Interact
We now have the tools to create and revise larger Python programs using the Python code editor and we can execute these programs using the Python interpreter.
The Blockly programs developed earlier used many of the common programming structures that are found in Python for calculation, sequence, decisions, and iterations. We can use the ability of Blockly to translate these Blockly programs into equivalent Python programs as an expedient way of learning the syntax of Python.
The following BlockPy workspace contains a program that counts two different categories of temperatures in the temperatures forecast for Blacksburg, Va. You can toggle between the Block view and the Text view to see the program in Blockly or in Python, respectively.
The important point of this demonstration is that the Python code generate by BlockPy is a complete and valid Python program that can be directly executed by the Python interpreter. We can now edit the code with the Python editor and create variations of this code. For example, try editing the example in the Spyder edit pane to change the string “Blacksburg, VA” to “Miami, FL” and run the Python code again. Be careful that you spell the string correctly and that there is exactly one space between the comma and the capital letter “F”.
The Anatomy of a Python Program¶
The Python code generated by the Blockly example will be used to examine some of the important aspects of a Python program.
Overall Structure¶
The following figure shows a Spyder edit pane for the example above with two regions identified. We will return soon to examine the detailed syntax of the individual statements. For now we want to get a “big picture” view.
The topmost part of the example code is an import statement. An import statement identifies a Python module that contains code to be reused in this program. The import statement shown here identifies a module named weather. The weather module contains the the function get_forecasts that is used in the program. The weather module also contains other functions that are part of the weather module.
The import statement is important because no serious Python program is written without reusing some code. In fact, most applications reuse code extensively. Not only does code reuse lower the cost of developing new applications but the reused code is also likely to have been tested and have had programming errors removed by previous uses. The Python developer community has made available a large number of modules some of which we will use later for data visualization.
The second area shown in the example code is the "main" program. This is the code where the execution of the program begins. When this code has been fully executed the program ends its execution.
Indentation¶
Another general characteristic of Python programs the importance of how the lines of code are indented. Python uses indentation to answer a question that all textual programming languages have to answer. In Python, the beginning of an iteration is signaled by the for keyword and the beginning of a decision is signaled by the if keyword. However, where is the end of the body of the code for the iteration? and which statements are in the different parts of the decision? Different languages answer this question in different ways. Blockly answers these questions by the shape of the blocks. All of the code in the body of an iteration is in the slot for the iteration block. Similarly, all of the code in the then part of a decision (the blocks performed when the decision's condition is true) are in the slot provided in the decision block. Python uses indentation to answer this question.
In the following figure, two vertical lines, one red and one blue, are used to identify where indentation has been used. You can see that every line that is part of the body of the iteration is indented as least four spaces and every line that is part of the decision is indented at least four additional (a total of eight) spaces. It is common practice to use four additional spaces at each new level of indentation.
Care is needed because spaces added by using the “Tab” key may be different than a sequence of spaces. While they may look the same to you they are different to the Python interpreter. Four spaces is four characters while one tab is only one character. Welcome to the world of computing where details do matter.
Punctuation using Colons
Another part of the important syntax of Python is the punctuation required for iteration and decisions. In natural languages (like English, Spanish, etc) punctuation is used to indicate the various parts of a sentence. In Python, the colon symbol (":") is used to indicate parts of the iteration and decision statements. The following figure shows where this punctuation is needed in our example program.
Punctuating Python Programs
As shown in the figure the colon is used at the end of the for statement that introduces an iteration. Also, colons are also used at the end of the if and elif statements that are parts of the decision statement. Although not shown, an else statement is also punctuated with a colon.
Comments¶
Understanding what (especially complex) code does may be difficult, so documenting what the code is intended to do is a sign of good craftsmanship. Each programming language has some means of including comments in the program text. These comments provide a way for the code’s author to convey to a human reader important information about the code. The meaning, purpose, or design are often documented in this way. Comments are written by a human for a human and are skipped over by the Python interpreter. The following figure shows our example code with comments added.
Python comments begin with a “#” (pound sign or hash symbol) and extend to the end of the line. As shown in the figure above comments can occupy either an entire line or only part of line. The sequence of comments preceding the main program each occupy the entire line. Such sequences are often used when there is a lot to say about something. Remember that these (and all) comments are skipped over by the interpreter. The two individual comments in the main program each occupy only part of a line. Each individual comment is meant to explain what the code on that line does. Comments like this are used when there is only a brief clarification that is needed.
Finally, there is no sense that the comments are “correct” or “meaningful” in any way because the comments are ignored by the Python interpreter. The comments for the main program could say that the program deals with crime rate in New York, NY even though this is clear incorrect to the human reader. As noted, the interpreter ignores the comments and does what the code says to do. The programmer is entirely responsible for ensuring that the comments are meaningful.
Error Messages
Just as in writing sentences in a natural language, we often make mistakes in expressing a statement in a programming language correctly. These are known in both cases as syntax errors. Spyder will automatically check the syntax of the code as you are typing in the editor pane and report problems to you. Also, Spyder will report such errors if you Run a program with syntax errors. To illustrate this syntax error reporting, a syntax error has been deliberately introduced into the code of one of the examples as shown in the following figure. The syntax error is in the line if temp < 70. Note that the colon (”:”) is missing in the incorrect version shown in the figure. The absence of the colon at the end of this line is a syntax mistake. Notice that Spyder has put a small warning icon in the left margin of the line of code that has a syntax mistake. If you hover the cursor over the icon you will see the message box that is shown in the figure. Once you fix the syntax mistake the warning icon will go away.
Error Messages
The editor will report only the first syntax error that it has found. If the code contains several syntax errors the syntax checking will have to be repeated once for each error. It is a good habit to periodically check for the presence of the warning icons in the code you are writing.
It may be that you overlook or ignore the syntax warnings provided by the Spyder editor and Run the program. The interpreter will be able to execute the program up to the point of the syntax error, but no farther because the syntax error makes the statement unintelligible to the interpreter. In this case the Python console pane (in the lower right corner) will report an error as shown in the above figure. This error message shows the line containing the syntax error (note the small caret symbol at the end of the line) and an error message (“SyntaxError: invalid syntax”).
Semantic Errors
Beyond their syntax languages also have a semantic aspect. Semantics refers to the meaning of what is expressed in the language. It is possible, of course, to make syntactically correct statements that are semantically meaningless. To say in English that “The sky is triangular.” is syntactically correct but it meaningless (outside of avant garde poetry or drug inspired rock songs).
Programs may also be syntactically correct by semantically wrong. For example, the correct way to convert a Temperature, T, from Fahrenheit to Celsius uses the formula (T-32)/1.8. If instead we write a program that uses the formula (32-T)/8.1 we will have a program that is syntactically correct but is not meaningful - it does not produce the output that corresponds to the meaning of a Celsius temperature in the real world. A program may be so semantically damaged that the Python interpreter cannot execute it. For example, in this code:
the interpreter is asked to perform a calculation of dividing by zero, an operation which has no mathematical meaning. In this case, the interpreter will abort the execution and report a run time error. Finding and fixing errors that occur at run time, called debugging, is often a tedious and difficult task.
Additional Help
You can get additional help with the Python syntax by looking at explanation and examples in the Python Tutorial. The definitive though harder to read source of help is the Python Language Reference. These documents can also be accessed from Spyder: in the Help menu select the Python documentation entry. There are also many other web tutorials and examples that you can find via a web search.