【问题标题】:Python: How to use a while loop and output the correct word countPython:如何使用 while 循环并输出正确的字数
【发布时间】:2016-10-10 21:58:01
【问题描述】:

这是我目前所拥有的:

while len(words) != 5:
        words = raw_input("Enter a 5 worded sentence: ").split()
        print "Try again. The word count is:", wordCount
if len(words) == 5:
        print "Good! The word count is 5!" 

问题是我明白了:

Enter a 5 worded sentence: d d d d
Try again. The word count is: 4
Enter a 5 worded sentence: d d d d d d 
Try again. The word count is: 4
Enter a 5 worded sentence: d d d d d 
Try again. The word count is: 4
Good! The word count is 5!

当我输入多于或少于 5 个字时,它会保持字数不变。

【问题讨论】:

  • 你在哪里初始化变量wordCount
  • 我把它放在while循环之前。 wordCount=len(words)
  • 确保发布生成输出的实际代码。照原样,您的代码将失败,因为在测试长度之前未定义 words

标签: python while-loop python-2.7 word-count


【解决方案1】:

由于 Python 不像其他一些语言那样具有 do-while 循环,因此这个习惯用法可以防止 raw_input 函数的重复,并确保循环至少运行一次。确保在获得新输入后更新word_count

while 1:
    words = raw_input("Enter a 5 worded sentence: ").split()
    word_count = len(words)
    if word_count == 5: break
    print "Try again. The word count is:", word_count
print "Good! The word count is 5!"

【讨论】:

  • 我们能不能不要教初学者写像while 1这样丑陋的东西?
  • 这并不正确。这是对 Zen 恕我直言的严重违反。
  • 在 Python 2 中,while 1 生成更高效的循环。在 Python 3 中,它不再起作用。
【解决方案2】:

你只需要重新排序你的一些逻辑:

# prompt before entering loop
words = raw_input("Enter a 5 worded sentence: ").split()
while len(words) != 5:
        print "Try again. The word count is:", len(words)
        words = raw_input("Enter a 5 worded sentence: ").split()

# no need to test len again
print "Good! The word count is 5!" 

【讨论】:

    【解决方案3】:

    在您接受输入后,变量 wordCount 应该在循环内更新。只有这样,它才会反映新的价值。像这样的东西:-

    while len(words) != 5:
        words = raw_input("Enter a 5 worded sentence: ").split()
        wordCount = len(words)
        print "Try again. The word count is:", wordCount
    if len(words) == 5:
        print "Good! The word count is 5!" 
    

    【讨论】:

      【解决方案4】:

      我认为您的代码 sn-p 缺少部分。无论如何,您应该在raw_input 之后评估wordCount,以便使用新值对其进行更新。

      wordCount = 0
      while wordCount != 5:
          words = raw_input("Enter a 5 worded sentence: ").split()
          wordCount = len(words)
          print "Try again. The word count is:", wordCount
      
      print "Good! The word count is 5!" 
      

      【讨论】:

      • 谢谢!我忘记了 wordCount = 0。
      【解决方案5】:
      def xlen(string_data):
          try:
              count = 0
              while 1:
                  string_data[count]
                  count = count + 1
          except(IndexError):
              print count
      
      xlen('hello')
      

      【讨论】:

        猜你喜欢
        • 2021-10-19
        • 1970-01-01
        • 2012-01-02
        • 2021-03-25
        • 2022-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多