Please Help Explain
Jakle
jakle1 at hotmail.com
Wed Nov 5 23:01:21 EST 2003
I was at a job interview one day and the owner of the start up company asked
me if I'd rather make $1000 dollars a day, or start off with a penny a day
and double the amount every day for 30 days. I was too lazy to sit down with
paper and pen to figure out how much the second choice came out to. But now
I'm learning python and just learned about recursive functions and
iteration, I figured I'd use those theories to figure out the problem. After
racking my brain trying to figure it out (I'm a noob to this stuff, and math
isn't my strong point), I came up with this formula: n = n*2. So I messed
around with it and came up with the following code:
+++++++++++++++++++++++++++++++++++++++
# penny.py 11-05-03
days = raw_input("How many days: ")
def calc(n, days):
i = 1
while i <= days:
n = n*2
i = i+1
return n/float(100)
print calc(1, int(days))
+++++++++++++++++++++++++++++++++++++++
I completely stumbled across it and it works. I just don't understand how
the value of n is assigned to the second n in "n=n*2" once it loops back
again. I would understand if it was a recursive function and passed as an
argument, but I don't think I completely understand how the "while"
statement handles variable values. I am learning from "How to Think Like a
Computer Scientist: Learning With Python", and it doesn't go into too much
depth about it, at the moment at least. I was wondering if anyone could shed
some light on my dilema. :-)
Thanks ahead of time.
More information about the Python-list
mailing list