I Cannot Print The Final Value Of A Variable
I'm new in Python and I'm trying the write to final value of recAdd on my fibonacci recursive version.  Here is my code: recAdd=0 def fibonacciRecursive(n):     global recAdd     i
Solution 1:
You need to dedent the print and place it after you call the function
def fibonacciRecursive(n):
    global recAdd
    if n == 1 or n == 0:        
        return n  # <-- should this be return 1?
    else:
        recAdd = recAdd + 1
        return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)
recAdd = 0
fibonacciRecursive(5)
print(recAdd)
You could encapsulate this in a wrapper
def fib_aux(n):
    global recAdd
    recAdd = 0
    fibonacciRecursive(5)
    print(recAdd)
Then just call
fib_aux(5)
Burying the logic in the function is awkward. Here is one way
def fibonacciRecursive(n, print_recAdd=True):
    global recAdd
    if n == 1 or n == 0:        
        retval = n  # <-- should this be 1?
    else:
        recAdd = recAdd + 1
        retval = fibonacciRecursive(n - 1, False) + fibonacciRecursive(n - 2, False)
    if print_recAdd:
        print recAdd
    return retval
Post a Comment for "I Cannot Print The Final Value Of A Variable"