GEOG 485:
GIS Programming and Software Development

Error message

Notice: unserialize(): Error at offset 14 of 14 bytes in variable_initialize() (line 1252 of /net/www/www.e-education.psu.edu/htdocs/drupal7/includes/bootstrap.inc).

Lesson 2 Practice Exercise 1 Solution

PrintPrint

Solution:

beatles = ["John Lennon", "Paul McCartney", "Ringo Starr", "George Harrison"]

for member in beatles:
    space = member.index(" ")
    print ("There is a space in " + member + "'s name at character " + str(space) + ".")

Explanation:

Given the info on the index method in the instructions, the trick to this exercise is applying the method to each string in the list. To loop through all the items in a list, you use a for statement that ends with 'in <list variable>', which in this case was called beatles. Between the words 'for' and 'in', you insert a variable with a name of your choosing. That variable will store a different list item on each iteration through the loop.

In my solution, I called this loop variable member. The member variable takes on the value of "John Lennon" on the first pass through the loop, "Paul McCartney" on the second pass through the loop, etc. The position of the first space in the member variable is returned by the index method and stored in a variable called space.

The last step is to plug the group member's name and the space position into the output message. This is done using the string concatenation character (+). Note that the space variable must be converted to a string before it can be concatenated with the literal text surrounding it.