Understanding and definition of the function:
Effects: reduce the difficulty of programming and code reuse
definition:
def <函数名> (<参数(0或多个)>):
<函数体>
return<返回值>
parameter:
Parameters are divided into non-optional parameters and optional parameters , the first parameter is non-optional
Function definition is designed to be variable parameters , neither the total number of parameters determined
def fact (n,*b):
s = 1
for i in range (1,n+1):
s*=i
for item in b:
s *=item
return s
#>>>fact(10,3) 10886400
#>>>fact(10,3,5,8) 43545600
Parameter passing in two ways: the location and name of the transfer transfer
def fact (n,m=1):
s = 1
for i in range(1,n+1)
s*=i
return s//m
fact (10,5) and the fact (m = 5, n = 10) the result is the same
Function's return value: return
Function can return a value, or may not,
return 0 return value can be returned, the return value may be a plurality of pass
def fact(n,m=1):
s = 1
for i in range (1,n+1):
s*=i
return s//m,n,m
#>>>fact(10,5) (725760,10,5)
#>>>a,b,c=fact(10,5)
#print(a,b,c) 725760 10 5
Local variables and global variables ,
Internal functions for local variables, local variables change does not affect the overall:
Reserved words , Ltd. Free Join :
Internal global function using local variables can become global variables
If you create a local variable is not true, in a global variable
lambda functions:
<Function name> = lambda <parameter>: <expression> for simple definition can function, the function name is represented by a row in the return result
f = lambda x,y: x + y
f(10,15)
#25
And code reuse recursive function:
Code reuse:
The same code can be reused when needed:
Functions and objects are two major forms of code reuse
Function: the code will be named in the code level to establish a preliminary abstract
Object: Properties and Methods <a> <b> and <a> <b> () function again on tissue Abstract
Modular design, function or object encapsulation by dividing a program into expression between the modules and the module
Tight coupling: a lot of communication between the two portions, made five independent existence i
Loosely Coupled: less communication between the two portions, there may be independently
Internal modules tightly coupled, loosely coupled between the modules
Recursive function: they own tune
Even key features:
Chain: there is a recursive calculation process chain
EXAMPLE group: one or more groups present embodiment does not require re-recursive
def fact(n):
if n == 0:
retutn 1#基例
else :
return n *fact(n-1)#链条
Tower of Hanoi:
count = 0
def hanoi(n,a,b,c):
global count
if n == 1
print("{}:{}->{}".format(1,a,b)
count += 1
else:
hanoi(n-1,a,c,b)
print("{}:{}->{}".format(n,a,b))
count += 1
hanoi(n-1,c,b,a)