Python: How to make a function that asks for the exact amount of words?

做~自己de王妃 提交于 2020-01-04 13:28:33

问题


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

回答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 = []
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.




回答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!

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:
    #...



回答3:


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




回答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.



来源:https://stackoverflow.com/questions/9407005/python-how-to-make-a-function-that-asks-for-the-exact-amount-of-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!