I. functions:
Functions are organized, reusable code snippets that implement a single, or associated function.
Function can improve the modularity of application and the reuse rate of code. You already know that Python provides many built-in functions, such as print().
But you can also create your own functions, which are called user-defined functions.
Define function rules:
The function code block begins with the keyword def followed by the function identifier name and parentheses ().
Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
The first line of the function optionally uses the document string - used to hold the function description.
The function contents start with a colon and are indented.
return [expression] ends the function and optionally returns a value to the caller. return without an expression is equivalent to returning None
Function definition example:
1 def function name (parameter 1, parameter 2): 2 ''' 3 this is a function of what problem to solve 4: param parameter 1: what does parameter 1 represent? 5: param parameter 2: what does parameter 2 represent? 6: Return: what to return 7 ''' 8 function body 9 return value 10 return return value
For example, define a function that evaluates the length of a string:
1 def my len (my STR): define a function 2 ''' 3 function used to calculate variable type length 4: param my_str: parameter content entered by the user 5: Return: returns the length of the parameter 6 ''' 7 count = 0 8 for val in my_str: 9 count += 1 10 return count 11 a = my_len("hightgood") 12 print(a) × output value 9
After defining a function, try not to use print, try to return the result.
You can know what is printed inside the function code. You can modify it at any time, but others don't know.
return in function:
1. Return to None
There are three situations:
(1) no return
(2) return None originally
(3) return is blank.
#nothing return
def my_print(parameter):
print("Welcome",parameter)
#return None
def my_print(parameter):
return None
#return
def my_print(parameter):
return #Generally used to end function body
2. Return a value
1 def my_len(my_str): #Defined function
2 #Calculate the length of variable type values
3 my_str = "goodnight"
4 count = 0
5 for val in my_str:
6 count += 1
7 return count #count That's the return value.
3. Return multiple values
1 def my_print():
2 return 11,22,33,[1,2,3]
3 a = my_print()
4 print(a)
5 #Print results:(11, 22, 33, [1, 2, 3])
The values after return are separated by commas and then returned as tuples
4. End function code
1 def my_print():
2 print('one')
3 return #encounter return Do not continue with the code below the function
4 print('two')
5 my_print() #Result: one
5. Supplement: receive multiple values
1 def my_print():
2 return 1,2,3
3 a,b,c=my_print()
4 print(a,b,c) #Equivalent to a Receive 1. b Receive 2. c Receive 3
5 def my_print():
6 return [4,5,6]
7 a,b,c=my_print()
8 print(a,b,c) #There are three values in a list. Use abc To receive is equivalent to unpacking
Parameters of the function:
1 def my_len(my_str): #There my_str Parameter, formal parameter and input object are uncertain. Multiple parameters can be separated by commas.
2 my_str = "goodnight"
3 count = 0
4 for val in my_str:
5 count += 1
6 return count
7 a = my_len("hightgood") #There hightgood It's the actual parameter. The input object is determined.
8 print(a)
Function parameter details:
1. Position parameters:
1 def demo_1(a,b): #Location parameter: a parameter that must be passed in by the user. If it is not passed, an error will be reported.
2 print(a,b)
3 demo_1(1,2) #Output result: 1 2 transfer parameters according to position
4 demo_1(b=1,a=2) #Output result: 2 1 by keyword
5 demo_1(1,b=2) #Output result: 1 2 mixed use, but it must be noted that first pass the parameter according to the position, then pass the parameter according to the keyword, otherwise an error will be reported.
2. Default parameters:
1 def welcome(name,sex='man'): #sex Is the default parameter
2 print('welcome %s,sex %s'%(name,sex))
3 welcome('zrh') #Output results: welcome zrh,sex man
4 welcome('lml','women') #Output results: welcome lml,sex women
5 #Default parameter if the parameter is not passed, the default value is used. If the default parameter is passed in, the value is passed in.
Traps for default parameters:
(1)
1 a = 18
2 def age(a1,a2=a):
3 print(a1,a2)
4 a = 20
5 age(10) #Output: 10 18
Internal principle:
(2)
Specific to variable data types
1 def demo(a = []):
2 a.append(1)
3 print(a)
4 demo() #Output results:[1]
5 demo() #Output results:[1] [1]
6 demo() #Output results:[1] [1] [1]
7 def demo_1(a = []):
8 a.append(1)
9 print(a)
10 demo_1([]) #Output results:[1]
11 demo_1([]) #Output results:[1]
12 demo_1([]) #Output results:[1]
Because variable type change is not to create a new space in memory, but to make changes based on the original, and lines 10-12 create three new blocks of memory.
3. Dynamic parameters:
Define dynamic parameters
1 def demo(*agrs): #Dynamic parameters entered by position, forming a tuple
2 pass
3 def demo_1(**kwargs): #Parameters passed in by keyword, forming a dictionary
4 pass
From the point of view of function definition: * performs aggregation, and combines one parameter into one tuple (* * is Dictionary)
From the point of view of function call: * to break up a list or tuple into multiple parameters (* * is the keyword form)
1 #Function definition angle:
2 def demo(*agrs): #Dynamic parameters entered by position
3 print(agrs)
4 demo(1,2,3,4,5) #Output result(1, 2, 3, 4, 5)
5 def demo_1(**kwargs): #Parameters passed in by keyword, forming a dictionary
6 print(kwargs)
7 demo_1(a=1,b=2,c=3) #Output result{'a': 1, 'b': 2, 'c': 3}
8 #Function call angle:
9 val = [1,2,3,4]
10 val2 = {'a':1,'b':2}
11 demo(*val) #take val Break it up into 1 2 3 4 and pass in the function
12 demo_1(**val2) #take val2 Break up into a=1 b=2,Then pass in the function
Explain why it is necessary to transfer parameters by position first and then by key data in the mixed parameter transfer:
1 def demo(*agrs,**kwargs): #*agrs and**kwargs The location is python Fixed dead
2 #So we must first pass parameters according to their positions.*agrs,And then pass parameters according to keywords.**keagrs
3 print(agrs)
4 print(kwargs)
5 demo(1,2,3,4,a = 1,b = 2)
6 # Output results:
7 # (1, 2, 3, 4)
8 # {'a': 1, 'b': 2}
Line 3 corresponds to the output of line 7
Line 4 corresponds to the output of line 8
Order when defining multiple parameters of different types:
1 def demo (position parameter 1, position parameter 2,*args, default parameter = x,**kwargs): 2 pass 3. It must be written in this way when multiple parameters are used in future career.
Format and principle:
Summary:
1 def demo(*args,**kwargs): #When the number of receiving parameters is uncertain, dynamic parameter transfer is used, and when used, dynamic parameter transfer is used.
2 pass
3 def demo_1(a,b,c): #Position parameter, several parameters must be passed in several values, most commonly used
4 pass
5 def demo_2(a,b=10): #Default parameter, when a large number of parameter information forms are used at the same time
6 pass
Nesting of functions:
1 #Nested calls to functions
2 def demo_1():
3 print(123)
4 def demo_2():
5 demo_1()
6 print(456)
7 demo_2()
8 # Output results:
9 # 123
10 # 456
11
12 #Function nesting definition
13 def demo_1():
14 print(123)
15 def demo_2():
16 print(456)
17 demo_2()
18 demo_1()
19 # Output results:
20 # 123
21 # 456
Note: when reading a function in memory, first read the definition function name (not the function body inside), and then return the function body when calling this function.
To adjust the contents of nested functions outside the function:
1 def case(x,y,z):
2 def new_case(a,b,c):
3 print('content',a,b,c)
4 new_case(x,y,z)
5 case(1,2,3)
6 #Output result content 1 2 3
Advance:
(1) to (7) indicate the code running sequence
*args and * * kwargs are just the way functions define parameters. They are not the same as mixed parameters.