首页 > 解决方案 > 我试图从输入中打印每个verible 的数量,但是我的代码并没有写出我想要的东西,尽管它看起来是正确的。Python

问题描述

这是代码,尽管它应该给出不同的输出,但它一直给我同样的东西。

    line = input('Car: ')
    while line:
      def word_count(str):
      counts = dict()
      words = str.split()

      for word in words:
          if word in counts:
              counts[word] += 1
          else:
              counts[word] = 1

      return counts 
    line = input('Car: ')

  print( word_count(line))

这是我得到的输出:

    {}

标签: pythonstring

解决方案


你可以试试

line = 'temp'
while line:
    line = input('Car: ')
    def word_count(str):
        counts = dict()
        words = str.split()

        for word in words:
            if word in counts:
                counts[word] += 1
            else:
                counts[word] = 1
        return counts

    if line:
        print(word_count(line))

推荐阅读