UnboundLocalError (赋值前引用的局部变量) Django



对于这个功能,我将解密一串莫尔斯电码,回到一个句子。 但是错误提示为UnboundLocalError(赋值前引用的局部变量"空格"(

我在网上研究,人们使用global来解决问题,但它对我不起作用,我只在本地这样做,所以我不希望它以后影响我的代码。

以下是我的观点:

def decipher(request):
"""The Decipher Page"""
MORSE_CODE_DICT = {'A': '.-', 'B': '-...',
'C': '-.-.', 'D': '-..', 'E': '.',
'F': '..-.', 'G': '--.', 'H': '....',
'I': '..', 'J': '.---', 'K': '-.-',
'L': '.-..', 'M': '--', 'N': '-.',
'O': '---', 'P': '.--.', 'Q': '--.-',
'R': '.-.', 'S': '...', 'T': '-',
'U': '..-', 'V': '...-', 'W': '.--',
'X': '-..-', 'Y': '-.--', 'Z': '--..',
'1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.',
'0': '-----', ', ': '--..--', '.': '.-.-.-',
'?': '..--..', '/': '-..-.', '-': '-....-',
'(': '-.--.', ')': '-.--.-'}
def decrypt(message):
# extra space added at the end to access the
# last morse code
message += ' '
decipherMsg = ''
citext = ''
for letter in message:
# checks for space
if letter != ' ':
# counter to keep track of space
space = 0
# storing morse code of a single character
citext += letter
# in case of space
else:
# if i = 1 that indicates a new character
space += 1
# if i = 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
val1 = request.GET.get('a1', '')
res = decrypt(val1)
return render(request, 'morse_logs/decipher.html', {'result': res})

我的网页:

{% block content %}
<h1>Decipher</h1>
<form action="" method="get" >
<textarea rows="10" cols="50" name='a1' ></textarea>
<textarea rows="10" cols="50" name='a2' > {{result}} </textarea>
<button type="submit" name="cipher">Cipher</button>

{% comment %}
<textarea rows="10" cols="50" name="a3" > {{result}} </textarea>
{% endcomment %}
</form>
{% endblock content  %}

发生这种情况的原因是您在为space变量赋值之前使用了该变量。例如,如果消息的第一个字符是空格,则可能会发生这种情况。

此外,您最好制作一个反向映射的字典,并检查citext是否至少包含一个字符:

MORSE_CODE_DICT_REV = {v: k for k, v in MORSE_CODE_DICT.items()}
def decrypt(message):
# extra space added at the end to access the
# last morse code
message += ' '
decipherMsg = ''
citext = ''
space = 0
for letter in message:
# checks for space
if letter != ' ':
# counter to keep track of space
space = 0
# storing morse code of a single character
citext += letter
# in case of space
else:
# if i = 1 that indicates a new character
space += 1
# if i = 2 that indicates a new word
if space == 2:
# adding space to separate words
decipherMsg += ' '
elifcitext != '':
# accessing the keys using their values (reverse of encryption)
decipherMsg += MORSE_CODE_DICT_REV[citext]
citext = ''
return decipherMsg

最新更新