Search code examples
pythonpython-3.xglobal-variablescounternameerror

Why do I get a NameError: name 'counter' is not defined, while I set the counter variable to global?


Below is my code. I don't know what I am doing wrong, but when I run this, I get NameError: name 'counter' is not defined. I'm learning Python from a textbook and according to the textbook my code is right. I can't find the difference between the textbook code and this code... I've seen other questions on stackoverflow about global variables, but I still can't figure out what I did wrong. Why do I get this error? And how to solve it?

UPDATE: I know what I did wrong. I should write counter = 0 above the function.

def rpower(a, n):
    'returns a to the nth power'
    global counter          # counts number of multiplications

    if n == 0:
        return 1
    # if n > 0:
    tmp = rpower(a, n//2)

    if n%2 == 0:
        counter += 1
        return tmp*tmp      # 1 multiplication

    else:
        counter += 2
        return a*tmp*tmp    # 2 multiplications

print(rpower(2, 10000))

Solution

  • May be your counter variable is declared outside of you function. Like:

    counter=0
    def rpower(a, n):
        'returns a to the nth power'
        global counter          # counts number of multiplications
    
        if n == 0:
            return 1
        # if n > 0:
        tmp = rpower(a, n//2)
    
        if n%2 == 0:
            counter += 1
            return tmp*tmp      # 1 multiplication
    
        else:
            counter += 2
            return a*tmp*tmp    # 2 multiplications
    print(rpower(2, 10000))