码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习:函数打包

时间:2015-01-26 21:07:44      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:python

一:首先看一个小程序

<span style="font-size:18px;">array = [0,1,2,3,4]
k = 0
for i in array:
    k = k + i
print k
</span>

这段程序的意思是求array数组每个元素的总和。

如果我想现在想求数组array2元素的总和的话,难道还要重复上面的操作吗?

<span style="font-size:18px;">array2 = [2,4,6]</span>
<span style="font-size:18px;">我们可以对程序打包,即自定义函数</span>
<span style="font-size:18px;">
</span>
<span style="font-size: 18px; background-color: rgb(102, 255, 255);"><strong>二:打包函数</strong></span>
<span style="font-size:18px;"></span><pre name="code" class="python">array = [0,1,2,3,4]
def sum(array):
    k = 0
    for i in array:
        k = k + i
    return k
print sum(array)



<span style="font-size: 18px; background-color: rgb(102, 255, 255);"><strong>三总结:</strong></span>
<span style="font-size:18px;"><span style="color:#ff0000;">(1)循环数组  for i in array:</span></span>
<span style="color:#ff0000;">(2)注意python代码的缩进,<span style="font-family: simsun; line-height: 21px; background-color: rgb(188, 211, 229);">同一层次的语句</span><span style="font-family: simsun; line-height: 21px; background-color: rgb(188, 211, 229);">必须</span><span style="font-family: simsun; line-height: 21px; background-color: rgb(188, 211, 229);">有相同的缩进。</span></span>
<span style="font-size:18px;"><span style="color: rgb(70, 70, 70); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(188, 211, 229);"></span></span><pre name="code" class="python">array = [0,1,2,3,4]
k = 0
for i in array:
        k = k + i
print k

上面的代码输出结果:10

<span style="font-size:18px;"><span style="color: rgb(70, 70, 70); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(188, 211, 229);">
</span></span>
<span style="font-size:18px;"><span style="color: rgb(70, 70, 70); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(188, 211, 229);">如果修改为:</span></span>
<span style="font-family: simsun; line-height: 21px; background-color: rgb(188, 211, 229);"></span><pre name="code" class="python" style="color: rgb(70, 70, 70); font-size: 14px;">array = [0,1,2,3,4]
k = 0
for i in array:
        k = k + i
        print k
那么输出结果为:
0
1
3
6
10
<span style="color:#ff6666;">(3)定义函数用关键字def</span>



<span style="font-size:18px;"><span style="color: rgb(70, 70, 70); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(188, 211, 229);">
</span></span>
<span style="font-size:18px;"><span style="color: rgb(70, 70, 70); font-family: simsun; font-size: 14px; line-height: 21px; background-color: rgb(188, 211, 229);">
</span></span>

Python学习:函数打包

标签:python

原文地址:http://blog.csdn.net/u013628152/article/details/43158715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!