Python Forum

Full Version: UnBoundLocalError
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
The error is suggesting that you are calling img before assigning it on line 67.
(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...
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.