Conquer python3 function

Keywords: Python

function

Functions are organized, reusable code snippets that implement a single, or associated function.

1. Definition of function

def test():                     #function
    print("in the test")
    return 0

def test1():                    #process
    print("in the test1")

x=test()
y=test1()
print(x)
print(y)

2. Significance of using function

import  time
def logger():
    time_format = '%Y-%m-%d %X'
    time_current = time.strftime(time_format)
    with open('a.txt','a+') as f:
        f.write('%s end action\n' %time_current)

def test1():
    print('in the test1')
    logger()
def test2():
    print('in the test2')
    logger()
def test3():
    print('in the test3')
    logger()

test1()
test2()
test3()

a. Save consistency
b. Scalability
c. Duplicate code

3. Return value of function
def test1():
    print("in the test1")
    pass                    #no return value

def test2():
    print("in the test2")
    return 0                #Return shaping

def test3():
    print("in the test3")
    return "a"              #Return character

def test4():
    print("in the test4")
    return "phk"            #Return string

def test5():
    print("in the test4")
    return [1,2,3,4]        #Return list

def test6():
    print("in the test6")
    return (1,2,3,4)        #Return tuple

def test7():
    print("in the test7")
    return {"name":"phk","age":22}     #Return dictionary

def test8():
    print("in the test4")
    return 0, 'hello', ['a', 'b', 'c'], {'name': 'alex'}    #Return mixed value
    
a=test1()
b=test2()
c=test3()
d=test4()
e=test5()
f=test6()
g=test7()
h=test8()               #When returned, the mixed value is treated as a tuple
print(a,b,c,d,e,f,g,h)

a.return value = 0 return none
b.return value = 1 return this value
c.return value > 1 returns a tuple of values

4. Function parameters
def test1(x,y):
    print(x)
    print(y)

#test1(1,2)  #Position parameter, actual parameter and formal parameter correspond one by one
#test1(y=2,x=1) #Keyword parameter position can not be corresponding
#test1(y=2,1)    #Keyword parameter and location parameter are mixed. Keyword parameter can no longer be in front of location parameter
test1(1,y=2)     #The one above will report an error
#Location parameters and keywords cannot be too many or too few

#Output result
1
2


def test2(x,y=2):   #Default parameters
    print(x)
    print(y)

#test2(1)    #The default parameter does not need to be written
#test2(1,3)
test2(1,y=3)

#Output result
1
3


def test3(*args):           #Parameter group parameter does not limit parameter limit,accept N Position parameters, converted to tuple form
    print(args)

test3(1,2,4,5,4,5,6)
#test3(*[1,2,3,4,5,6])   #args=([1,2,3,4,5,6])

#Output result
(1, 2, 4, 5, 4, 5, 6)


def test4(x,*args):         #Mixed use of position parameter and parameter value parameter
    print(x)
    #print(y)
    print(args)

test4(1,21,3,4)

#Output result
1
(21, 3, 4)


def test5(x=1,*args):      #Mix default and parameter group parameters
    print(args)
    print(x)

test5(2,2,3,4)
# test5(*([1,2,3,4]))       #The result shows that if the default parameter is in front of the parameter group parameter, the default parameter will take the first parameter of the parameter group parameter, and the current default parameter will be modified. Otherwise, it will not be. If the content of the default parameter needs to be modified, the keyword parameter should be used. It is recommended to place the default parameter after the parameter value parameter

#Output result
(2, 3, 4)
2


def test6(x,y,z=2,*args):
    print(x)
    print(y)
    print(args)
    print(z)

test6(1,2,1,2,3,4,5)

#Output result
1
2
(2, 3, 4, 5)
1


def test7(**kwargs):    #accept N Key parameters, convert to dictionary
    print(kwargs)

test7(name="phk",age=22)

#Output result
{'name': 'phk', 'age': 22}


def test8(x,y,z=6,*args,**kwargs):          #Mixed use of multiple parameters
    print(x)
    print(y)
    print(args)
    print(z)
    print(kwargs)

test8(1,2,34,5,6,7,name="phk",age=22)

#Output result
1
2
(5, 6, 7)
34
{'name': 'phk', 'age': 22}

5. Local variable and global variable

school="old boy"
names=["wr",'gcc']
def change_name(name):
    global school               #global Allow the function to modify the global variable. If there is no global variable, change the variable into a global variable global)
    print("Before amendment:",name,school,names)
    name='jcy'                  #Local variable. This function is the scope of this variable
    school='hut'
    names[1]="zxq"              #If the global variable is a list, a dictionary, or a collection, it can be modified inside the function, string, or shape
    print("After amendment:",name,school,names)


name='phk'
change_name(name)
print(name)
print(school)
print(names)

6. recursion

def case(n):
    print(n)
    if int(n/2)>0:
        return case(int(n/2))
    print("-->",n)

case(10)

Features of recursion:
a. There must be a clear end condition
b. For each deeper level of recursion, the problem scale of recursion should be smaller than that of the previous level
c. Low recursion efficiency

7. Higher order function
#Higher order function                       #One function as an argument to another
def func(x,y,f):
    return f(x)+f(y)

n=func(1,-3,abs)
print(n)

#Output result
4

 

 

 



Posted by owned on Tue, 31 Mar 2020 11:13:47 -0700