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

Ivan Avery Frey ivan.avery.frey at gmail.com
Sun Jul 3 18:23:17 UTC 2011


Exercise 1. Count the number of words in a string. Assume words are separated by 
a space.

s=raw_input("Please enter a string of words with a space between each word. ")
wordlist=s.split(" ")
print "The number of words in the string is", str(len(wordlist))+"."

Exercise 2. What does an index of -1 mean in a list or a string.

I would suspect this is undefined. But testing this on a string and a list, a 
negative index -i (i>0) gives the nth item in the string or list counting the 
items in reverse order. Accordingly a negative index -i (i > 0) is defined on a 
string or a list when 1 <= i <= len(string or list).

Exercise 3. Print the first five numbers using their english words:

List_of_numbers_spelled_out=['one','two','three','four','five']
for s in List_of_numbers_spelled_out:
     print s

Exercise 4. Guido van Rossum is the author of Python and his name was used 
because he has a 2 part last name and it was useful to demonstrate slices.

Exercise 5. Print an asterisk histogram from a list of numbers.

vals=[ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
for v in vals:
     asterisks=""
     for i in range(v):
         asterisks += "*"
     print asterisks


More information about the Courses mailing list