A: First look at a small program
<span style= "FONT-SIZE:18PX;" >array = [0,1,2,3,4]k = 0for i in array: k = k + iprint k</span>
This procedure means to ask for the sum of each element of array arrays.
If I wanted to find the sum of the array2 elements of the array now, would you like to repeat the above operation?
<span style= "FONT-SIZE:18PX;" >array2 = [2,4,6]</span>
<span style= "FONT-SIZE:18PX;" > We can package the program, that is, the custom function </span>
<span style= "FONT-SIZE:18PX;" ></span>
<span style= "FONT-SIZE:18PX; Background-color:rgb (102, 255, 255); " ><strong> II: Packaging Functions </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:< C2/>k = k + i return kprint sum (array)
<span style= "FONT-SIZE:18PX; Background-color:rgb (102, 255, 255); " ><strong> Three summary:</strong></span>
<span style= "FONT-SIZE:18PX;" ><span style= "color: #ff0000;" > (1) Loop array for I in array:</span></span>
<span style= "color: #ff0000;" > (2) Note the indentation of Python code, <span style= "Font-family:simsun; line-height:21px; Background-color:rgb (188, 211, 229); " > The same level of statement </span><span style= "Font-family:simsun; line-height:21px; Background-color:rgb (188, 211, 229); " > Must </span><span style= "Font-family:simsun; line-height:21px; Background-color:rgb (188, 211, 229); " > has the same indentation. </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 = 0for i in array: k = k + IP Rint K
The above code output results: 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); " > If modified to:</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 = 0for i in array: k = k + i print K
Then the output is:
013610
<span style= "color: #ff6666;" > (3) define function with keyword 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 Learning: function packaging