hey guys, silly random question i am kind of naive on.
i have a function:
Code:
def balance(x, months, r, paymentrate):
""" assumes minimum balance payment """
balance = x
for y in range(months):
balance = (balance * (1-paymentrate))*(1+(r/12))
print round(balance,2)
return balance
nevermind how terribly written or inefficient it is. i am a beginner, and am building blocks! something curious happens when i run said function in the global environment in python (is it called injection when i hit f5 and the function is "loaded" into the global environment? what is that called?.) if i load the function into the global environment, and then call:
Code:
balance(4213,12,.2,.04)
the following is the resulting output:
Code:
>>> balance(4213,12, .2, .04)
4111.89
4013.2
3916.89
3822.88
3731.13
3641.58
3554.19
3468.89
3385.63
3304.38
3225.07
3147.67
3147.670552638328
huh, curious.
so i am learning currently how environments are structured and how procedural assignments are localized in their respective environments, so i found this to be an interesting case. my naive understanding of environments was that in this case it should have (within the balance function, using my assignments for x, months, r that i enter in the global environment) run the for loop 12 times, and the resulting 12 rounded cases support that argument.
the last line of unrounded code, which is just what appears to be a print of the last value of balance (without rounding) is curious though. and where i am confused and concerned that i may not understand environments as well as i thought i do.
the
was intentional, mostly because i like seeing if i can break my functions and see what happens when i do.
i thought that return would do nothing, as it simply stores a value and exits the function at that step.
so out of curiosity i attempted to have pythontutor.com stepthrough the function for me, and following is the resulting output.
curious, no "3147.670552638328" here. then i noticed that i was calling balance within that script, and not in the global environment, so i tried that in python:
Code:
input:
def balance(x, months, r, paymentrate):
""" assumes minimum balance payment """
balance = x
for y in range(months):
balance = (balance * (1-paymentrate))*(1+(r/12))
print round(balance,2)
return balance
balance(4213,12, .2, .04)
output
>>>
4111.89
4013.2
3916.89
3822.88
3731.13
3641.58
3554.19
3468.89
3385.63
3304.38
3225.07
3147.67
>>>
so i appear to have a fundamental misunderstanding.
can anybody help me understand where i've derailed in my understanding of global environments, environments, the return statement, and "injecting" into global environments? i guess i don't really know the difference between "loading" the function into the global environment as opposed to calling the function from the script like in the last example, which gets output into the global environment?
im lost