2

Here's what I have so far:

import string

So I have the user write a 5 worded sentence asking for only 5 words:

def main(sentence = raw_input("Enter a 5 worded sentence: ")):
    if len(words)<5:
        words = string.split(sentence)
        wordCount = len(words)
        print "The total word count is:", wordCount

If the user inputs more than 5 words:

    elif len(words)>5:
        print 'Try again. Word exceeded 5 word limit'

Less than 5 words:

    else:
        print 'Try again. Too little words!'

It keeps stating that:

UnboundLocalError: local variable 'words' referenced before assignment
2
  • When asking a question, please say what the problem is.
    – Kitsune
    Feb 23, 2012 at 4:08
  • string.split(sentence)? You should upgrade to Python2 or better so you can say sentence.split() Feb 23, 2012 at 4:24

4 Answers 4

2

Your problem is that you are calling len(words) before the variable words exists. This is in the second line of your second code block.

words = []
while len(words) != 5:
  words = raw_input("Enter a 5 worded sentence: ").split()
  if len(words) > 5:
    print 'Try again. Word exceeded 5 word limit'
  elif len(words) < 5:
    print 'Try again. Too little words!'

Note that in python, default arguments are bound at time of function definition rather than at function call time. This means your raw_input() will fire when main is defined rather then when main is called, which is almost certainly not what you want.

4
  • 2
    What more is there to explain...?
    – wim
    Feb 23, 2012 at 4:17
  • Hahaha I know what you mean, but you know what I meant :P now it's better
    – salezica
    Feb 23, 2012 at 4:19
  • One thing that might be good to explain is why calling raw_input() in the def is such a bad idea..
    – DSM
    Feb 23, 2012 at 4:21
  • yeah, added a note about that
    – wim
    Feb 23, 2012 at 4:24
1

Read your own output :): the 'words' variable is referenced before assignment.

In other words, you are calling len(words) before saying what 'words' means!

def main(sentence = raw_input("Enter a 5 worded sentence: ")):
    if len(words)<5: # HERE! what is 'words'?
        words = string.split(sentence) # ah, here it is, but too late!
        #...

Try defining it before attempting to use it:

words = string.split(sentence)
wordCount = len(words)
if wordCount < 5:
    #...
0
0

Take the inputs using raw_input(). Do the wordcount using Split() and then re-read if it is not equal to 5.

0

UnboundLocalError: local variable 'words' referenced before assignment

This means exactly what it says. You are trying to use words before the part where you figure out what the words actually are.

Programs proceed step-by-step. Be methodical.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.