【发布时间】:2020-05-05 18:27:01
【问题描述】:
对于这个功能,我要解密一串摩尔斯电码,回到一句话。 但是错误提示说 UnboundLocalError (local variable 'space' referenced before assignment)
我在网上研究过,人们使用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})
我的html:
{% 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变量未设置在for循环之外,因此如果它首先采用else,它在分配它之前使用space。跨度> -
我也尝试在 for 循环之外初始化
space = 0。但它给了我 ValueError at /decipher/,'' is not in list -
这是一个不同的错误:)
-
你能分享完整的回溯吗?
-
回溯:内部 34 中的文件“Documents/morse_log/m_env/lib/python3.7/site-packages/django/core/handlers/exception.py”。响应 = get_response(request) 文件“ Documents/morse_log/m_env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request)
标签: django-templates django-views