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

Django中UnboundLocalError求助:摩尔斯电码解密函数报错

Fixing UnboundLocalError in Morse Code Decipher Function

Hey there! Let's tackle that UnboundLocalError you're hitting in your Morse code decryption function. The error happens because the space variable is only defined inside the if letter != ' ' block—so if the first character in your input is a space, the code tries to run space += 1 before space has ever been assigned a value. Using global didn't work here because this is a local variable initialization issue, not a scope problem with global variables.

The Solution: Initialize the Local Variable Upfront

The fix is straightforward: initialize space as a local variable before your for loop runs, so it exists regardless of which branch of the conditional executes first. Here's how to update your decrypt function:

def decrypt(message):
    # extra space added at the end to access the
    # last morse code
    message += ' '
    decipherMsg = ''
    citext = ''
    space = 0  # Initialize space here, outside the loop
    for letter in message:
        # checks for space
        if letter != ' ':
            # counter to keep track of space: reset to 0 when we hit a non-space
            space = 0
            # storing morse code of a single character
            citext += letter
        # in case of space
        else:
            # increment space counter
            space += 1
            # if space == 2 that indicates a new word
            if space == 2:
                # adding space to separate words
                decipherMsg += ' '
            else:
                # accessing the keys using their values (reverse of encryption)
                decipherMsg += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)]
                citext = ''
    return decipherMsg

What Changed?

  • We moved space = 0 to the top of the decrypt function, right after setting up other local variables. This ensures the variable exists in the function's local scope from the start.
  • When we hit a non-space character, we still reset space to 0 (preserving your original logic for tracking consecutive spaces).
  • Now, even if the first character is a space, space has already been assigned a value, so space += 1 won't throw an error.

Optional Optimization

As a side note, looking up keys by values with list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)] is inefficient for longer messages. You can pre-create a reverse dictionary once (outside the decrypt function) to speed this up:

# Inside the decipher function, before defining decrypt
REVERSE_MORSE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()}

# Then replace the lookup line in decrypt with:
decipherMsg += REVERSE_MORSE_DICT[citext]

Dictionary lookups are O(1), so this will make your decryption much faster, especially with large inputs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:43:11