简体   繁体   中英

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. This is the 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:

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?

This is my terminal output: the 64 is from print(days)
the 1 comes from print(calculate_stock(stock, sales_base_line, days))
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:

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. When it prints, it doesnt exit the function. You need to move return into the else statement if you want the function to exit there. Currently, it just prints, then continues the loop and starts going backwards from 64 down to 1, which is why you get 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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