【问题标题】:return statement not passing valuereturn 语句不传递值
【发布时间】:2019-09-19 17:14:58
【问题描述】:

Total newbie here......下面代码中的return语句没有传递函数计算的值。有人有什么想法吗?


def pagos(B,P,r,c):
    UB = (B-P)*(1+(r/12)) 

    if (c==12):
        print(UB) #This is to establish if UB is actually reaching return statement#
        return UB
    c +=1
    pagos(UB,P,r,c)

P=200
B=10000
r=0.2
c=0

R = pagos(B,P,r,c)

print("Answer :"+str(R))```

9472.628606761953                                                                                                                                                                  
Answer :None

【问题讨论】:

  • 如最后两行所示,UB 被打印,但返回传递值“无”
  • 因为在您定义的函数中,它什么也不返回。输入return 以返回结果值。

标签: python recursion return


【解决方案1】:

你忘了在递归调用中使用return

def pagos(B,P,r,c):
    UB = (B-P)*(1+(r/12)) 

    if (c==12):
        print(UB)
        return UB
    c +=1
    return pagos(UB,P,r,c)

【讨论】:

  • 是正确的,这是让刚接触编程的人的常见错误:return 不会退出整个调用堆栈,它只是返回到调用它的位置并从那里继续执行。通过从嵌套调用返回结果,一大堆返回可以“冒泡”答案一直回到开头。
【解决方案2】:

对于递归过程,您应该 return pagos(UB,P,r,c)

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2019-03-09
    • 2020-01-04
    • 2016-12-29
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多