Search code examples
pythonfunctionvariablesgloballocal

Python Local Variable As Counter


Using Python 3.7.

Is there any way to use a local variable as a counter? I tried and received error:

UnboundLocalError

I did find a recommendation to use a glbal variable which is working, but if possible I would prefer to use a local variable.

Thanks, -w

Working code using global variable for counter:

count = 0
def my_collatz(number):

    global count
    count +=1
    if int(number)%2 == 0:
        r = int((number)//2)
    else:
        r = int(((number * 3) + 1))
    print('Attempt : ' + str(count) + ',' + str(r))

    if r != 1:
        return my_collatz(int(r))

print('Please enter a number : ')
number=input()
my_collatz(int(number))

Solution

  • One possible solution is to move the count variable as parameter to the function and increment it each call:

    def my_collatz(number, count=1):    
        if number % 2 == 0:
            r = number // 2
        else:
            r = (number * 3) + 1
    
        print('Attempt : ' + str(count) + ',' + str(r))
    
        if r != 1:
            return my_collatz(r, count + 1)
    
    print('Please enter a number : ')
    number=input()
    my_collatz(int(number))
    

    Prints:

    Please enter a number : 
    6
    Attempt : 1,3
    Attempt : 2,10
    Attempt : 3,5
    Attempt : 4,16
    Attempt : 5,8
    Attempt : 6,4
    Attempt : 7,2
    Attempt : 8,1
    

    Other solution is to not use count at all, and instead make the function a generator (using yield). Then you can use enumerate() to obtain your number of steps:

    def my_collatz(number):
        if number % 2 == 0:
            r = number // 2
        else:
            r = (number * 3) + 1
    
        yield r
    
        if r != 1:
            yield from my_collatz(r)
    
    print('Please enter a number : ')
    number=input()
    
    for count, r in enumerate(my_collatz(int(number)), 1):
        print('Attempt : ' + str(count) + ',' + str(r))