这是我到目前为止的内容:
import string
所以我让用户写一个5词的句子,只问5个词:
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
如果用户输入的单词超过5个:
elif len(words)>5:
print 'Try again. Word exceeded 5 word limit'
少于5个字:
else:
print 'Try again. Too little words!'
它不断指出:
UnboundLocalError: local variable 'words' referenced before assignment
最佳答案
您的问题是在变量len(words)
存在之前您正在调用words
。这是第二个代码块的第二行。
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!'
请注意,在python中,默认参数是在函数定义时绑定的,而不是在函数调用时绑定的。这意味着您的
raw_input()
将在定义main时而不是在调用main时触发,这几乎肯定不是您想要的。