UnboundLocalError at / local variable 'key' referenced before assignment

Question:

here is my code i am facing this error i am not able to find the error fix the error shoow

def get_key(res_by):
    if res_by == '#1':
        key = 'transaction_id'
    elif res_by == '#2':
        key = 'created'
    return key
def get_chart(chart_type, data, results_by, **kwargs):
        plt.switch_backend('AGG')
        fig = plt.figure(figsize=(10,4))
        key = get_key(results_by)
        

thats the code

Asked By: SunnyDS

||

Answers:

The problem is that in case both conditions fail, key is not assigned any value, but you return key. You thus need to specify a value in the else case:

def get_key(res_by):
    if res_by == '#1':
        key = 'transaction_id'
    elif res_by == '#2':
        key = 'created'
    else:
        key = something  # ← specify a value if the two conditions fail
    return key
Answered By: Willem Van Onsem

What if res_by is not #1 or #2? It wont be defined. Try this.

def get_key(res_by):
    if res_by == '#1':
        key = 'transaction_id'
    elif res_by == '#2':
        key = 'created'
    else:
        key = None
    return key
Answered By: Thavas Antonio
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.