Python Forum
UnBoundLocalError - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: UnBoundLocalError (/thread-27230.html)



UnBoundLocalError - Seaninho - May-30-2020

Hello to everyone!

I'm trying to create a code using Python but I have a problem.
It gives me this error:
Error:
File "/opt/miniconda3/bin/sfipick", line 268, in <module> image = rsf2image(0) File "/opt/miniconda3/bin/sfipick", line 67, in rsf2image return img UnboundLocalError: local variable 'img' referenced before assignment
I will post here the part of the code where the problem is:
def rsf2image(i3):
    global byte
    ppm = '%s%d.ppm' % (name,i3)
    if not os.path.isfile(ppm):
        command = '< %s %s n3=1 f3=%d | %s %s | %s %s > %s' % \
            (byte,sfwindow,i3,sfgrey,args,ppmpen,args,ppm)
        if os.system(command) or not os.path.isfile(ppm):
            sys.stderr.write('Failed to execute "%s"\n\n' % command)
            sys.exit(3)
        ppms.append(ppm)
    img = PhotoImage(file=ppm)
    return img

...
image = rsf2image(0)
Can someone please help me with this?

Thank you very much


RE: UnBoundLocalError - menator01 - May-30-2020

The error is suggesting that you are calling img before assigning it on line 67.


RE: UnBoundLocalError - pyzyx3qwerty - May-30-2020

(May-30-2020, 09:45 AM)menator01 Wrote: The error is suggesting that you are calling img before assigning it on line 67.
He defines img on line 66

(May-30-2020, 08:59 AM)Seaninho Wrote: Hello to everyone!

I'm trying to create a code using Python but I have a problem.
It gives me this error:
Error:
File "/opt/miniconda3/bin/sfipick", line 268, in <module> image = rsf2image(0) File "/opt/miniconda3/bin/sfipick", line 67, in rsf2image return img UnboundLocalError: local variable 'img' referenced before assignment
I will post here the part of the code where the problem is:
def rsf2image(i3):
    global byte
    ppm = '%s%d.ppm' % (name,i3)
    if not os.path.isfile(ppm):
        command = '< %s %s n3=1 f3=%d | %s %s | %s %s > %s' % \
            (byte,sfwindow,i3,sfgrey,args,ppmpen,args,ppm)
        if os.system(command) or not os.path.isfile(ppm):
            sys.stderr.write('Failed to execute "%s"\n\n' % command)
            sys.exit(3)
        ppms.append(ppm)
    img = PhotoImage(file=ppm)
    return img

...
image = rsf2image(0)
Can someone please help me with this?

Thank you very much
Is this your full code? The problem might be somewhere else too...


RE: UnBoundLocalError - azajali43 - May-31-2020

You can solve UnboundLocalError by changing the scope of the variable that complains. You need to explicitly declare the global variable. The scope of the variable x in the printx function is global. You can verify the same by printing the value of x in the terminal and it will be 6.