标签:python
一:首先看一个小程序
<span style="font-size:18px;">array = [0,1,2,3,4] k = 0 for i in array: k = k + i print k </span>
如果我想现在想求数组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
<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
原文地址:http://blog.csdn.net/u013628152/article/details/43158715