[Courses] [python] Lesson 3: Fun with Strings and Lists

lenore borisova orangegirl at gmail.com
Mon Jul 4 18:17:57 UTC 2011


Sorry for the multiple posts earlier; the emails did not group with the same
lessons as I had expected so my bad. Thanks all for not flaming me while I
caught up with all of you and sorted it out ;)

Below is my current lesson homework:

LESSON 3

1. How would you count the number of words in a single string?
   Assume words are separated by spaces ... don't worry about
   things like newlines, commas or hyphens.

You would use the space as your check (plus 1 since the last word does not
have a trailing space).
Example would be:

    veggies = "peas beans spinach corn squash"

    i  = veggies.split(" ")
    count = 0

    for i in veggies        :
            if i == " "     :
                count = count + 1

    print count + 1



2. What does an index of [-1], or another negative number mean in a
   list or string? Take a guess, then try it and see if you were right.


It starts the count from the end of the list rather than the beginning:

petstore = "dogs cats birds snakes fish hamsters"
pet = petstore.split()
print "you choose a",pet[-2]

Gets you fish and this gets you birds:

petstore = "dogs cats birds snakes fish hamsters"
pet = petstore.split()
print "you choose a",pet[-4]

and if you type in a negative number that is greater than the number of
items in the list, you get the following error: IndexError: list index out
of range




3. Who is Guido van Rossum and why am I using him as an example?

He is the Dutch author of the Python programming language. His full name is
a good surname example since it should be "van Rossum" rather than just
"Rossum"


4. Rewrite the exercise from lesson 2, the one where
   you printed "one", "two", "three", "four", "five",
   using a list instead of a series of if-elif.


nums  = "one two three four five"
word = nums.split(" ")
print word[0:]


5. This one's a little harder, but give it a try if you have time.
 :  Plot a histogram graph from a list of numbers, with each number in
   the list on its own line.


digits = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]

for i in digits:
        for histo in range(0,i):
                print "*",
        print



--Lenore


More information about the Courses mailing list