Skip to content Skip to sidebar Skip to footer

Python: How To Make A Function That Asks For The Exact Amount Of Words?

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: ')): i

Solution 1:

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 = []
whilelen(words) != 5:
  words = raw_input("Enter a 5 worded sentence: ").split()
  iflen(words) > 5:
    print'Try again. Word exceeded 5 word limit'eliflen(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.

Solution 2:

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

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

defmain(sentence = raw_input("Enter a 5 worded sentence: ")):
    iflen(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:
    #...

Solution 3:

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

Solution 4:

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.

Post a Comment for "Python: How To Make A Function That Asks For The Exact Amount Of Words?"