Tim Johnson wrote: > Hi Guys,
Hi Tim! > Very simple question, I imagine. > > this code throws of off a "counter not defined error". Instead of retyping the error message it is better to cut and paste the traceback, e. g. Traceback (most recent call last): File "tmp.py", line 6, in <module> print counter NameError: name 'counter' is not defined > Can you help? > > def word_counter(word, string): > counter = 0 > for item in string: > if item == word: > counter = counter + 1 > print counter When you assign a value to a variable inside a function that variable is only known inside that function and only during the execution of that function. When you move the print statement into the function it should work as the following session in the interactive interpreter demonstrates: >>> def word_counter(word, string): ... counter = 0 ... for item in string: ... if item == word: ... counter = counter + 1 ... print counter ... >>> word_counter("the", "the house by the sea") 0 Oops! by default a for loop iterates over the characters in a string, not the words. Let's try with a list of words: >>> word_counter("the", ["the", "house", "by", "the", "sea"]) 2 If you want to allow a string argument you can modify your function to iterate over for item in string.split(): ... Another improvement would be to have the function return the counter instead of printing it. That way you can do other things with it: >>> def word_counter(word, string): ... counter = 0 ... for item in string.split(): ... if item == word: ... counter = counter + 1 ... return counter ... >>> phrase = "the house by the sea" >>> num_words = len(phrase.split()) >>> print 100.0 * word_counter("the", phrase) / num_words, "percent of all words are 'the'" 40.0 percent of all words are 'the' _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor