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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十五楼亮哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值