python, importing function from other file which uses variable in the functions file
Question: 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.


Answer: 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.

