GEOG 485:
GIS Programming and Software Development

Lesson 2 Practice Exercise 3 Solution



import arcpy

input = arcpy.GetParameterAsText(0)
score = int(input)

if score > 89:
    print ("A")
elif score > 79:
    print ("B")
elif score > 69:
    print ("C")
elif score > 59:
    print ("D")
    print ("F")


This exercise requires accepting an input parameter, so in my solution, I imported arcpy so that I could make use of the GetParameterAsText method. If you run this script directly in Spyder, you can provide the input value for GetParameterAsText by going to Run > Configuration per file, checking the Command line options box, and entering a score in the Command line options text box. An alternative to using GetParameterAsText would be to use the Python function input() to read from the keyboard. Because the input parameter is being stored as a text string, I include an additional step that converts the value to an integer. While not critical in this instance, it's generally a good idea to avoid treating numeric values as strings when possible. For example, the number 10 treated as a string ("10") is considered less than 2 treated as a string ("2") because the first character in "10" is less than the first character in "2".

An 'if' block is used to print the appropriate grade for the inputted score. You may be wondering why all of the expressions handle only the lower end of the grade range and not the upper end. While it would certainly work to specify both ends of the range (e.g., 'elif score > 79 and score < 90:'), it's not really necessary if you evaluate the code as the interpreter would. If the user enters a value greater than 89, then the 'print "A"' statement will be executed and all of the other conditions associated with the if block will be ignored. Code execution would pick up with the first line after the if block. (In this case, there are no lines after the if block, so the script ends.)

What this means is that the 'elif score > 79' condition will only ever be reached if the score is not greater than 89. That makes it unnecessary to specify the upper end of the grade range. The same logic applies to the rest of the conditions in the block.