1. Calling functions
ABS () method, calling the absolute value function
ABS (1) ABS ( -1) ABS (1.1)
CMP () method, Comparison function
CMP (() CMP (2,1) CMP
Data type conversions
Int (' 123 ') int (1,23) str (1)
2. Defining functions
Define an absolute value function
def my_abs (x): if x >= 0:return x else:return-x
Return returns the function value and represents the end of the call
Null function
Def Kong (): Pass
Pass represents empty, if not fill in will error
Parameter check
def my_abs (x): If not isinstance (x, (Int,float)): Raise TypeError (' bad operand tpye ') if x >= 0:ret Urn x else:return-x
Isinstance (value, type) to check if the value is the corresponding type
Raise represents throwing an error and ending without executing the code behind
Return multiple values
def sum (a,b,c): x = a + b y = b + c z = a + c return z/y
3. Parameters of the function
Default parameters
def power (x): return x * x
def power (x,n=2): s = 1 while n > 0:n = n-1 s = S * x return s
Variable parameters
Def calc (*numbers): sum = 0 for n in numbers:sum = sum + N * N return sumnums = [1,2,3]calc (*nums)
Variable parameters allow automatic assembly of arbitrary parameters into tuples
Keyword parameters
def person (name,age,**kw): print ' name: ', Name, ' Age: ', age, ' other: ' kwkw = {' City ': ' Beijing ', ' job ': ' Engineer '}person (' Jack ', 27,**kw)
The keyword parameter allows automatic assembly of any parameter into a dictionary
Parameter combinations
def func (a,b,c=0,*args,**kw): print ' a= ', A, ' b= ', B, ' c= ', C, ' args= ', args, ' kw= ', Kwargs = (1,2,3,4) kw = {' X ':} func (*ar GS,**KW) A = 1 b = 2 c = 3 args = (4) kw = {' X ': 99}
4. Recursive functions
Recursive functions
def fact (n): if n = = 1:return 1 return n * Fact (N-1) fact (1) fact (5)
This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1726069
Python Learning Note 2 function