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

Erin McLaughlin emclaughlin1215 at gmail.com
Fri Jul 15 14:16:21 UTC 2011


> ================== Homework ======================
>
> 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.
s = 'This is an epic test string of nine words.'
w = s.split(' ')
print 'That string had', len(w), 'words.'
> 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.
I would say that it would throw an error, but apparently it gives you 
the last item in the list.  Go Python!
> 3. Who is Guido van Rossum and why am I using him as an example?
He probably created Python.
> 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']
for s in nums :
     print s
> 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.
vals = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
for v in vals :
     stars = ''
     for i in range(0, v) :
         stars += '*'
     print stars


More information about the Courses mailing list