0

how do you add the output of a sum back into the input?

eg. i = 100

print i/2
which will give you 50 (obviously)
then i want to divide the answer by 2 and then the answer of that by 2 and so on ad infinitum

thanks in advance

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by juzzy
1

Then you will probably use something called recursion.
That is when a function calls itself. It is used in these kind of situations.

def recurse(num,count):
    if count == 10:
        return
    else:
        print num/2
        recurse(num/2, count+1)

recurse(100.0,1)

See, the recursive function has something called a base case. That is something that the recursive function knows what to do with and can stop recursing. So in this case our base case is that if the count is equal to ten then the function will return, therefore returning to the previous function. That in turn returns to the function it was called from up till the top one. But if it does not match the base case we print our new result and continue with recursion.

Hope that helps

EDIT: I made it 100.0 so that it would use decimal places where necessary.

Votes + Comments
nice example
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.