这是我到目前为止所拥有的:
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 时触发,这几乎肯定不是您想要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)