問題盯滚,關(guān)于魔力教程里面復利題目序矩。
t = 1
while t <= 8:
amount = 100
amount = amount * (1+0.05) ** t
print 'year' + ' ' + str(t) + ': $' + str(amount)
t += 1
print amount
print t
這段代碼如果放到函數(shù)中
def invest(amount, rate, time):
amount = int(raw_input("principal amount:"))
t = 1
while t <= time:
amount = amount * (1+rate) **t
print 'year' + ' ' + str(t) + ': $' + str(amount)
t += 1
print amount
invest(100, 0.05, 8)
不把**t去掉會變大
老師解答
amount = 100
amount = amount * (1+0.05) ** t
原因就在這里
自己運行的代碼秧均,在while循環(huán)里面锉罐,每次都設置amount = 100
而函數(shù)里面,while循環(huán)里面的amount 每次都會改變的
可以修改如下
QQ圖片20160303170657.png
QQ圖片20160303170717.png
a
第二個例子的_amount = amount不懂
b
因為你原來的代碼:amount = amount * (1+rate) **t
b
這個右邊amount每次都是不一樣的赏枚,加上amount=_amount后每次都設置他為100亡驰,就不會改變了
b
_amount保存的是傳進來的100
a
就是說不在函數(shù)里面的時候,每個循環(huán)的初始饿幅,都會自動設成100凡辱,而在函數(shù)里面的時候,如果invest(100)調(diào)用栗恩,只是在第一遍的時候透乾,100。后面就取函數(shù)內(nèi)部的值了嗎
b
是的