Introductionin Python it is assumed that 4 spaces are indented, and the indented code can be understood as a block, but using indentation also requires attention that sometimes different indents produce different results, and then we look at a columnExample: Customizing a function, and finally returns the sum of squares of the passed values
def Calc (numbers): = 0 for in numbers: = sum + N * n return sum< /c12>Print (Calc ([1,2,4]))
The above code returns the normal value: 21 Then change the code a little bit.
def Calc (numbers): = 0 for in numbers: = sum + N * n return sum< /c12>Print (Calc ([1,2,4]))
What is the value returned now: The result returns 1
Why return 1, carefully analyzed, the code I will return the indentation, then return is based on each loop for the return of a value, and return when the first condition is satisfied when the execution is not down, so when the first 1 o'clock, Sum=0+1*1=1, Return 1 is no longer in the back loop. Return does not indent so return and for are the same level, and when all of the for execution is done, the return is executed and the final result is returned.
Easier to understand by replacing return with print
def Calc (numbers): = 0 for in numbers: = sum + N * n print (sum) Print (Calc ([1,2,4]))
None
and indent Print
def Calc (numbers): = 0 for in numbers: = sum + N * n print (sum) Print (Calc ([1,2,4]))
1521None
Because print does not perform as if the condition is not met by return, the value of each loop is printed out.
Summary
Use indentation to understand the meaning of each line indentation, otherwise the returned result may not be the correct result
Note: pursuer.chen Blog:http://www.cnblogs.com/chenmh This site all the essays are original, welcome to reprint, but reprint must indicate the source of the article, and at the beginning of the article clearly give the link. Welcome to the exchange of discussions |
Python indentation issues