【问题标题】:Python: How to make a function that asks for the exact amount of words?Python:如何制作一个要求确切字数的函数?
【发布时间】:2012-03-13 12:02:13
【问题描述】:

这是我目前所拥有的:

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

【问题讨论】:

  • 提问时,请说出问题所在。
  • string.split(sentence)?你应该升级到 Python2 或更好,这样你就可以说sentence.split()

标签: python python-2.7 word-count


【解决方案1】:

您的问题是您在变量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 中,默认参数是在函数定义时绑定的,而不是在函数调用时绑定的。这意味着您的 raw_input() 将在定义 main 时触发,而不是在调用 main 时触发,这几乎肯定不是您想要的。

【讨论】:

  • 还有什么要解释的...?
  • 哈哈哈我知道你的意思,但你知道我的意思:P 现在好多了
  • 一件事可能很好解释是为什么在 def 中调用 raw_input() 是个坏主意..
  • 是的,添加了一个注释
【解决方案2】:

阅读您自己的输出 :):“words”变量在赋值之前被引用。

换句话说,您在说出“单词”的含义之前调用了 len(words)!

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

在尝试使用它之前尝试定义它:

words = string.split(sentence)
wordCount = len(words)
if wordCount < 5:
    #...

【讨论】:

    【解决方案3】:

    使用 raw_input() 获取输入。 使用 Split() 进行字数统计 如果不等于5则重新读取。

    【讨论】:

      【解决方案4】:

      UnboundLocalError: 赋值前引用了局部变量 'words'

      这正是它所说的。您正在尝试在找出 words 实际是什么的部分之前使用 words

      程序逐步进行。有条不紊。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-24
        • 2015-07-03
        • 2019-05-04
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 2019-11-01
        • 2022-10-19
        相关资源
        最近更新 更多