You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python关键字计数器统计异常求助:重复输入关键字未正确计数

Fixing Your Python Keyword Counter's Counting Bug

Let's break down what's going wrong with your keyword counter and fix it up step by step.

The Root of the Problem

Looking at your loop logic, there are two critical issues throwing off the count:

  • You’re using a counter variable that’s unnecessary and actively breaking the count. Every time you match a keyword, you first set dict1[x] = counter (which is always 0), then increment it to 1. Even if the keyword appears multiple times, this overwrites the existing count back to 0 before adding 1—so you’ll never get a number higher than 1.
  • Your conditional check after setting dict1[x] = counter is redundant because you just added the key to the dictionary, so the else block will never run.

Fixed Code

Here’s the corrected version of your script, with clear explanations of the changes:

phrase = input('Enter Python source code:').split(' ')
keywords = {"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try"}
dict1 = {}

for x in phrase:
    if x in keywords:
        # Use dict.get() to safely get the current count (0 if not present) and increment by 1
        dict1[x] = dict1.get(x, 0) + 1

# Sort the dictionary alphabetically by keyword
sorted_dict = dict(sorted(dict1.items()))

# Clean up the print loop by unpacking key-value pairs
for keyword, count in sorted_dict.items():
    print(f"{keyword}: {count}")

Key Improvements

  • Removed the useless counter variable—we don’t need it because we’re tracking counts directly in the dictionary.
  • Used dict.get(x, 0) to handle both cases (keyword seen before or not) in one line: if the keyword is already in dict1, we get its current count; if not, we default to 0. Then we add 1 to that value.
  • Simplified the final print loop by unpacking key-value pairs directly, making the code cleaner and easier to read.

Testing this with input while while will now correctly output while: 2 as expected.

内容的提问来源于stack exchange,提问作者Nevin Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:28:16