Django中UnboundLocalError求助:摩尔斯电码解密函数报错
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 = 0to the top of thedecryptfunction, 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
spaceto 0 (preserving your original logic for tracking consecutive spaces). - Now, even if the first character is a space,
spacehas already been assigned a value, sospace += 1won'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

