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
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
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
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
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
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