Search code examples
pythonfunctionrecursionreturncall

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


Solution

  • 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)