Each lesson in this course includes some simple practice exercises with Python. These are not submitted or graded, but they are highly recommended if you are new to programming or if the project initially looks challenging. Lessons 1 and 2 contain shorter exercises, while Lessons 3 and 4 contain longer, more holistic exercises. Each practice exercise has an accompanying solution that you should carefully study. If you want to use the USA.gdb referenced in some of the solutions you can find it here.
Remember to choose File > New in PyScripter to create a new script (or click the empty page icon). You can name the scripts something like Practice1, Practice2, etc. To execute a script in PyScripter, click the "play" icon.
Practice 1: Say hello
Create a string variable called x and assign it the value "Hello". Display the contents of the x variable in the Console.
- Practice 1 Solution
Solution:
x = "Hello" print (x)
Explanation:
The first line of the script tells the Python code interpreter to set aside space in the computer's memory to hold a value, to refer to that space in memory by the name x and to store the text string "Hello" in that space. The memory space is typically referred to as a variable. Unlike some languages that require declaring a variable and defining the type of data it will hold before assigning a value to it, Python allows variables to be defined without explicitly specifying their type. The data type (string, number, etc.) is inferred by the Python code interpreter based on the kind of value you're assigning to the variable.
The second line of the script tells the interpreter to print the contents of the x variable to the Python Interpreter.
Note that this already simple script could be simplified even further by doing away with the x variable and plugging "Hello" into the print statement directly as literal text:
print ("Hello")Note also that this script does not include lines that import arcpy since the script does not require any ArcGIS functionality.
Practice 2: Concatenate two strings
Create a string variable called first and assign to it your first name. Likewise, create a string variable called last and assign to it your last name. Concatenate (merge) the two strings together, making sure to also include a space between them.
- Practice 2 Solution
Solution:
first = "James" last = "Franklin" full = first + " " + last print (full)
Explanation:
In this script, two string variables are used to hold the two name pieces. The two pieces are merged together using the concatenation character (+ in Python). A space is inserted between them using a space within quotes.
If you wanted to display the name pieces last name first and with a comma in between, you would change the 'full' statement as follows:
full = last + ", " + first
Practice 3: Pass a value to a script as a parameter
Example 1.6.4 shows the use of the arcpy.GetParameterAsText() function. This function is typically used in conjunction with an ArcGIS script tool that has been designed to prompt the user to enter the required parameters. However, it is possible to supply arguments to the script from within PyScripter. To do so, you would select Run > Configuration per file, check the Command line options checkbox, then enter the arguments something like this:
C:\PSU\geog485\Lesson1.gdb\USA\us_cities C:\PSU\geog485\Lesson1.gdb\USA\us_cities_buffered "10 miles"
Note that the arguments to the two feature class parameters are unquoted, while the argument to the buffer distance string parameter is provided in double quotes.
For this exercise, write a script that accepts a single string value using the GetParameterAsText method. The value entered should be a name, and that name should be concatenated with the literal string "Hi, " and displayed in the console. Test the script from within PyScripter, entering a name (in double quotes) in the Command line options text box as outlined above prior to clicking the Run button.
- Practice 3 Solution
Solution:
import arcpy name = arcpy.GetParameterAsText(0) print ("Hi, " + name)Explanation:
There are other means of obtaining user input from the PyScripter IDE, but this course is focused on executing scripts from within ArcGIS, so the exercise asked you to use arcpy's GetParameterAsText function. That means that, unlike the first two exercises, this script requires importing arcpy. As mentioned, the script can be executed from within PyScripter by entering the name parameter as a command line option. GetParameterAsText is zero-based, so the script is set up to get parameter 0 (the first and only parameter).
Note that it would also be acceptable to do away with the name variable as follows:
print ("Hi, " + arcpy.GetParameterAsText(0))
Practice 4: Report the geometry type of a feature class
Example 1.6.2 demonstrates the use of the Describe function to report the spatial reference of a feature class. The Describe function returns an object that has a number of properties that can vary depending on what type of object you described. A feature class has a spatialReference property by virtue of the fact that it is a type of Dataset. (Rasters are another type of Dataset and also have a spatialReference property.)
The Describe function's page in the Help lists the types of objects that the function can be used on. Clicking the Dataset properties link pulls up a list of the properties available when you describe a dataset, spatialReference being just one of several.
For this exercise, use the Describe function again; this time, to determine the type of geometry (point, polyline or polygon) stored in a feature class. I won't tell you the name of the property that returns this information. But I will give you the hint that feature classes have this mystery property not because they're a type of Dataset as with the spatialReference property, but because they're objects of the type FeatureClass.
- Practice 4 Solution
Solution:
import arcpy fc = "C:/PSU/Geog485/Lesson1.gdb/USA/us-boundaries" desc = arcpy.Describe(fc) shapeType = desc.shapeType print ("The geometry type of " + fc + " is " + shapeType)Explanation:
This script begins like the one in example 1.6.2 since both require using the Describe function. As mentioned in the exercise instructions, you can see that the Describe function provides access to a spatialReference property by looking at the Describe function's help page for Datasets. In other words, if the object you're describing is a type of Dataset, it has a spatialReference property.
In this case, you were asked to determine the geometry type of a feature class and given the hint that the property you need belongs to objects of the type FeatureClass. This hint should have led you to click the FeatureClass properties link on the Describe function's Help page and scan through the list of properties until you found shapeType. The solution above reads the shapeType property, stores the return value in a variable, and then inserts that value into a user-friendly print message that also includes the name of the feature class.
Practice 5: Do some simple math and report your results
Create a variable score1 and assign it a value of 90. Then create a variable score2 and assign it a value of 80. Compute the sum and average of these values and output to the Console the following messages, by replacing the x with your scores:
The sum of these scores is x.
Their average is x.
In constructing your messages, you're probably going to want to concatenate text strings with numbers. We'll cover this more in Lesson 2, but this requires converting the numeric values into strings to avoid a syntax error. The str() function can be used to do this conversion. For example, I might output the score1 value like this:
print('Score 1 is ' + str(score1))
- Practice 5 Solution
Solution:
score1 = 90 score2 = 80 sum = score1 + score2 avg = sum / 2 print("The sum of these scores is " + str(sum) + ".") print("The average is " + str(avg) + ".") #Alternatively... #score1 = 90 #score2 = 80 # #print("The sum of these scores is " + str(score1 + score2) + ".") #print("The average is " + str((score1 + score2) / 2) + ".")Explanation:
This script begins with a couple of statements in which the score1 and score2 variables are created and assigned values. There are two approaches shown to displaying the required messages. The first shows creating variables called sum and avg to store the two simple statistics requested. The values held in those variables are then inserted into a pair of print() statements using string concatenation. Note the use of the str() function to convert the numbers into strings for the purpose of concatenating with the message text.
The second approach ("commented out" using the # character) shows how the script could be written without bothering to create the sum and avg variables. The required math can be embedded right within the print() statements. Note that in the statement that outputs the average the addition of the values held in score1 and score2 is enclosed in parentheses. If these parentheses were omitted, the script would still run, but would produce an incorrect average because algebra's order of operations would cause score2 to be divided by 2 first, then score1 would be added to that product.
A couple of other points can be made about this script:
You might be thinking that the second approach is pretty slick and that you should be striving to write your scripts in the shortest number of lines possible. However, in terms of performance, shorter scripts don't necessarily translate to higher performing ones. In this instance, there is practically no difference. And the second approach is a bit harder for another coder (or yourself at some later date) to interpret what's going on. That's a very important point to take into consideration when writing code.
You'll often see, including in the ArcGIS documentation, Python's format() function used to insert values into larger strings, eliminating the need for the concatenation operator. For example, we could display our sum message like so:
print('The sum is {}.'.format(sum))
With the format() function, curly braces are used within a string as placeholders for values to be inserted. The string (enclosed in single or double quotes) is then followed by .format(), with the desired value plugged into the parentheses. Note that the values supplied are automatically converted into a string format and any number of placeholders can be employed. For example, we could combine the two messages like so:
print('The sum is {}. The average is {}.'.format(sum, (score1 + score2) / 2))