Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using same variable that is created in function into another function

I want to use ‘number’ variable that was created out of the function and use it in couple functions and also give it an initial value 0, but it gives "local variable ‘number’ referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.

lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A reason you get the error, local variable 'number' referenced before assignment, is you did not used global keyword to declare that you will use THE number variable even in go_back().

A simple solution is to use global in the go_back(), as follows:

def go_back():
   global number # -> as you did in `go_forward()`.
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

However, you need to play it safe when using global because it makes hard to track variable changes. Instead, it would be better to pass number value as an argument in the functions.

For more information to use global keyword, see an answer of the question here: Why are global variables evil?

In addition, I recommend you to read this article about Alternatives to Using Globals in Python

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading