Lokesh
Lokesh

Reputation: 3112

Alternate to global variable in Python

I am implementing a recursive function in which I need to remember a global value. I will decrement this value in every recursive call and want it to reflect in other recursive calls also.

Here's a way I've done it.

First way:

global a
a = 3
def foo():
    global a
    if a == 1:
        print 1
        return None
    print a
    a -= 1    # This new 'a' should be available in the next call to foo()
    foo()

The output:

3
2
1

But I want to use another way because my professor says global variables are dangerous and one should avoid using them.

Also I am not simply passing the variable 'a' as argument because 'a' in my actual code is just to keep track of some numbers, that is to track the numbering of nodes I am visiting first to last. So, I don't want to make my program complex by introducing 'a' as argument in every call.

Please suggest me whatever is the best programming practice to solve the above problem.

Upvotes: 1

Views: 4323

Answers (2)

franckfournier
franckfournier

Reputation: 364

Try this : Use a parameter instead of a global variable. Example code

a = 3


def foo(param):
        if param == 1:
            print 1
            return None
        print param
        foo(param - 1)

foo(a)

Upvotes: 6

chepner
chepner

Reputation: 532538

Don't use a global; just make a a parameter to the function:

def foo(a):
    print a
    if a == 1:
        return None
    foo(a-1)

foo(3)

Upvotes: 7

Related Questions