Good evening.
I can not understand the global and local variables. I wanted to make it as simple as this:

counter = 1 def incr(): counter += 1 counterString = counter.__str__() return counterString print incr() + ' : ' + someString 

It gives an error that the variable is local and has not yet been declared ...

UnboundLocalError: local variable 'counter' referenced before assignment

How to be in this case?
PS print incr() + ' : ' + someString is executed in a loop

    2 answers 2

    The thing is that python perceives global variables with a small "but". If you have decided to change it, then please use global . If not, then it works.

    It turns out that three slightly different codes will work:

     counter = 1 def incr1(): global counter counter += 1 counterString = counter.__str__() return counterString def incr2(): ncounter = counter + 1 counterString = ncounter.__str__() return counterString def incr3(): counterString = counter.__str__() return counterString print(incr1() + ":" + incr2() + ":" + incr3()) 

    As a result:

    2: 3: 2

    • Thanks for the answers now figured out. In general, I expected that the increment is similar to PHP's, because i ++ would be enough. - xenoll

    If I am not mistaken, it is necessary in the incr () function to declare counter as a global variable:

     def incr(): global counter counter += 1 counterString = counter.__str__() return counterString 
    • Thank you, everything works - xenoll