这是我到目前为止所拥有的:
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
最佳答案
您的问题是您在变量 words
存在之前调用 len(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 中,默认参数是在函数定义时绑定(bind)的,而不是在函数调用时绑定(bind)的。这意味着您的 raw_input()
将在定义 main 时触发,而不是在调用 main 时触发,这几乎肯定不是您想要的。
关于Python:如何创建一个要求准确字数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9407005/