adhamncheese
adhamncheese

Reputation: 111

How can I count and display my recursive steps in Python?

I am trying to count how many times my program goes through my recursive statement and gives me my result. This is the code:

def days(amt):
    day = 0
    new = (amt*.05) + amt - 10

    if amt == 0:
        return 0

    elif amt == '':
        return

    elif new >= 0 and new <= 1000:
        day += 1
        return days(new)

print("In {} days, you'll have {}".format(day,new))

So when you call the function days(100), it calculates that it takes 15 days to reach new amount which less than 0 or greater than 1000 (and then it stops bc it satisfies the second elif condition).

So I want my output to look like this In 15 days, you'll have -7.892....

My problem is no matter where I place the counter, it doesn't count.

Upvotes: 1

Views: 1020

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

To persist the count you need to either use some global variable or use a parameter to do the counting then return both the count and the amt:

def days(amt, day=1):
    new = (amt * .05) + amt - 10

    if amt == 0:
        return day, 0

    elif 0 <= new <= 1000:
        return days(new, day + 1)
    return  day, new

Which gives you:

In [2]: print("In {} days, you'll have {}".format(*days(100)))
In 15 days, you'll have -7.89281794114

You cannot set day = 0 anywhere in the function as every call is going to reset it to 0. I also removes elif amt == '' as I cannot see how a function that takes an int/float should ever equal to an empty string.

Upvotes: 3

Related Questions