简体   繁体   English

从 function Python 获取错误的返回值

[英]Get the wrong return value from function Python

I'm currently working on an Python function from which I need to get the return value to calculate other things.我目前正在研究 Python function ,我需要从中获取返回值来计算其他内容。 This is the function:这是 function:

def calculate_stock(stock, stock_base_line, days):
    sales_after_stock = stock - (stock_base_line/30)
    if sales_after_stock > 0:
        days +=1
        calculate_stock(sales_after_stock, stock_base_line, days)        
    else:
        print(days)  
    return days    

This is the call from this function:这是来自 function 的调用:

stock = 123
sales_base_line=57.461538
days = 0
xd = calculate_stock(stock, sales_base_line, days)+2
print(xd)

Since in the call of the function days is 64, I actually hoped that the variable xd is then 66. however, only 3 is returned, so the function returns 1. What is the reason for this and how can I fix it?由于在调用 function 的days是 64 时,我实际上希望变量xd是 66。然而,只返回 3,所以 function 返回 1。这是什么原因,我该如何解决?

This is my terminal output: the 64 is from print(days)这是我的终端 output:64 来自print(days)
the 1 comes from print(calculate_stock(stock, sales_base_line, days)) 1 来自print(calculate_stock(stock, sales_base_line, days))
output output

The point is in recursion and the way you use it.关键在于递归和你使用它的方式。 Try to return the result of recursion and move the last return into else block:尝试return递归的结果并将最后一个return移动到 else 块中:

def calculate_stock(stock, stock_base_line, days):
    sales_after_stock = stock - (stock_base_line/30)
    if sales_after_stock > 0:
        days +=1
        return calculate_stock(sales_after_stock, stock_base_line, days)        
    else:
        return days  

You terminal output is 64 becuase print(days) is in the else block.您的终端 output 是 64,因为 print(days) 在 else 块中。 When it prints, it doesnt exit the function.打印时,它不会退出 function。 You need to move return into the else statement if you want the function to exit there.如果您希望 function 在那里退出,您需要将 return 移到 else 语句中。 Currently, it just prints, then continues the loop and starts going backwards from 64 down to 1, which is why you get 1.目前,它只是打印,然后继续循环并开始从 64 倒退到 1,这就是你得到 1 的原因。

def calculate_stock(stock, stock_base_line, days):
    sales_after_stock = stock - (stock_base_line/30)
    if sales_after_stock > 0:
        days +=1
        return calculate_stock(sales_after_stock, stock_base_line, days)
    else:
        print(type(days))
        print(days)
        return days

stock = 123
sales_base_line = 57.461538
days = 0
xd = calculate_stock(stock, sales_base_line, days) + 2
print(xd)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM