1

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

The day +=1 under the elif statement ends up doubling the number of days. So you can take that out and leave the day + 1 in the recursive call. Otherwise, perfect! Thanks!
Make day = 1 in the function call.
Yep, forgot I had the +=
Perfect! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.