Python实战:四周实现爬虫系统Q群讨论笔记1

问题,关于魔力教程里面复利题目。

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

这段代码如果放到函数中

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循环里面,每次都设置amount = 100
而函数里面,while循环里面的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
就是说不在函数里面的时候,每个循环的初始,都会自动设成100,而在函数里面的时候,如果invest(100)调用,只是在第一遍的时候,100。后面就取函数内部的值了吗
b
是的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容