【问题标题】:UnboundLocalError (Local variable referenced before assignment) DjangoUnboundLocalError(赋值前引用的局部变量)Django
【发布时间】: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


【解决方案1】:

发生这种情况的原因是因为您在为其赋值之前使用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 += ' '
                elif citext != '':
                    # accessing the keys using their values (reverse of encryption)
                    decipherMsg += MORSE_CODE_DICT_REV[citext]
                    citext = ''
        return decipherMsg

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2012-11-14
    • 2013-11-29
    • 2019-09-02
    • 1970-01-01
    • 2015-06-14
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多