[Tutor] Tutor Digest, Vol 132, Issue 51

Alan Gauld alan.gauld at btinternet.com
Sat Feb 21 18:05:01 CET 2015


On 21/02/15 16:48, Tim Johnson wrote:
> Hi Guys,

Hi, please don't send the entire digest, some folks pay by the byte.
Ideally send a new mail to tutor at python.org instead of replying to an 
existing digest.

Also change the subject to something meaningful so folks an find
it in the archives.

> *def word_counter(word, string):*
> *    counter = 0*
> *    for item in string:*
> *        if item == word:*
> *            counter = counter + 1*
> *print counter*

Your last line is outside the function so counter is invisible to it.

You need to indent the line so it is in line with the for... line

However I suspect this function is not going to do what you hope it 
will. item will iterate over the characters in the string not the words.
You probably want something like

def word)_counter(word, string):
     count = 0
     for group in string.split():
         if group == word:
            count += 1
     return count

hth

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list