1

I currently have a python program which imports a function from a file, but this function uses a variable which is stored in the file the functon is called from.

The code for the main function:

from second_file import second

while True: 
    print second(param)

The code for the second function:

 counter = 0
 def second(param):
     counter +=1
     return param + counter

When running the programm i get the following error:

local variable 'counter' referenced before assignment

So the question is, how can i get the "second" function to use this variable.

mat
  • 77
  • 1
  • 1
  • 6
  • is there any reason that you inialize `counter` outside of the function? – R Nar Nov 27 '15 at 19:08
  • if i set the counterinside the function it will get reset with each function-call right? – mat Nov 27 '15 at 19:09
  • 1
    This has nothing to do with imports. In Python functions, you can call variables from a higher scope as long as it's read-only. If you write to the variable (like your `counter += 1`) it becomes local to the function and gives this error. – Two-Bit Alchemist Nov 27 '15 at 19:09
  • @Two-Bit Alchemis so is there a wac of changing the variable localy to then store it globaly(until the next call) – mat Nov 27 '15 at 19:20
  • It's really hard to understand the problem you're having because I have no idea what the structure of your package is. Yes, there's almost certainly a way to retain that value. Global variables are not the answer, though. – Two-Bit Alchemist Nov 27 '15 at 19:27
  • @two-bit-alchemist ty for your help/answer, it works now using global variables. – mat Nov 27 '15 at 19:32

1 Answers1

0

Since you are modifying global variable you need to explicitly state that using

global counter
counter += 1

Otherwise here variable scope is limited to function and in this function scope, counter is not defined and hence the error.

Rozuur
  • 4,115
  • 25
  • 31
  • the problem is, global doesnt help, the value wont increment/remain incremented when callingthe function the next time – mat Nov 27 '15 at 19:17
  • That is the behaviour of global vairables, and this answers your question. What exact behaviour is required when you call the second function, can you show the output for 3-4 subsequent calls to second? – Rozuur Nov 27 '15 at 19:28
  • ty for the help, the global variables work now, i used them incorrectly the first time – mat Nov 27 '15 at 19:33