我无法打印一个变量的最终值 [英] I cannot print the final value of a variable

查看:169
本文介绍了我无法打印一个变量的最终值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的Python和我想的写 recAdd 在我递归斐波纳契版本的最终值。这是我的code:

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
    if n==1 or n==0:        
        return n
    else:
        recAdd=recAdd+1
        return fibonacciRecursive(n-1)+fibonacciRecursive(n-2)
    print(recAdd)

在我打电话给我的功能,它只返回斐波那契数值,而不是 recAdd 。我要同时打印它们。我应该怎么做才能打印 recAdd 值?

After I called my function, it returns only fibonacci value and not recAdd.I want to print both of them. What should I do to print the recAdd value?

推荐答案

您需要迪登的打印,并将其放置在调用函数之后

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

这篇关于我无法打印一个变量的最终值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆