GEOG 485:
GIS Programming and Software Development

Lesson 1 Practice Exercise 5 Solution

PrintPrint

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:

  1. 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.
  2. 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))