1. Define function
def function name ():
Content
def function name (parameter 1, parameter 2,...):
Content
*If the function is not called actively, the function will not execute
2. Function call
Function name ()
Function name (argument 1, argument 2,...)
3. Notes in function
""" """
4.parameter
//Parameter:
(1)Position parameter: the number of formal parameters and real parameters must be consistent
def hh(name,age):
print name,age
hh(age = 12,name = 'hh')
(2)Default parameter: the number of formal parameters and actual parameters can be different and can be changed
def mypow(x,y=2):
print pow(x,y)
mypow(7,2)
mypow(2)
//When there is only one argument value, the default value is the second power of x. when there are two arguments, the default value is invalid!
(3)Variable parameter: the number of parameters is uncertain
*args :args Tuple data type, variable name,General use args
def mysum(*args):
print args
sum = 0
for item in args:
sum += item
print sum
mysum(1,2,3,4)
*nums:To unpack a list, set, or tuple, you only need to add the variable name before unpacking*
def mysum(*args):
print args
sum = 0
for item in args:
sum += item
print sum
nums = [1,2,3,4,5,6]
mysum(*nums)
(4)Key parameters:**kwargs :A dictionary can pass any number of key-value
def guan(**kwargs):
print kwargs
guan(name=['westos'], age=18, hobbies=['code', 'running'])
5. Return value of function
When the result of function operation needs further operation, return the value with return
If there is no return value, the default is none
python can indirectly return multiple values to form tuples
Receive with one parameter to form tuple
Two parameters receiving, single data
Once the return function is completed
6.Scope of function variable
(1)local variable
//The ordinary variables defined in the function only function within the function. After the function execution, the variables are deleted automatically
a = 1
def han():
#global a
a = 5
print 'in',a,id(a)
han()
print 'out',a,id(a)
print a,id(a)(2)global variable
global a Declare global variables
s = random.random() Randomly generate 0~1 Number between
7.Decorator of function
(1)Definition: take a function as an argument and return an alternative function
(2)Function: add function to function without changing original function
//Exercise 1:
def fun1(): Function 1
print 'have a nice day!'
def fun2(): Function 2
print 'happy'
def outer(fun): Function decorator
def inner():
print '******'
fun1()
print '******'
return inner
fun = outer(fun1)
fun()
//Exercise 2:
def say(age):
print 'man is %d years old'%age
def outer(fun):
def inner(age):
if age < 0:
age = 0
fun(age)
return inner
say = outer(say)
say(-10)
//Example 3: grammar sugar
def desc(fun):
def inner():
print 'happy'
fun()
print '***'
return inner@desc #If you need to decorate a function, add this statement before that function
def login():
print 'login'login()