1 Basic syntax and characteristics of functionsDefinition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functionsFeatures:
- Reduce duplicate code
- To make the program extensible
- Make programs easier to maintain
Syntax Definitions:
1 def Sayhi ():# function name 2 print("Hello, I ' m nobody! " )3 4# Call function
can take parameters
1 #the following code2A, B = 5,83c = a**b4 Print(c)5 6 7 #change to write with a function8 defCalc (x, y):#x, y are formal parameters9res = x**yTen returnRes#returns the function execution result One Ac = Calc (A, B)#A, B is the argument, the result is assigned to the C variable - Print(c)
2 return value
To get the result of the function execution, you can return the result using the return statement
Attention:
- The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
- If return is not specified in the function, the return value of this function is None
deftest01 ():Passdeftest02 ():return0deftest03 ():return3,'Hello',['Amy','Bob'],{'name':'Alex',' Age': 21}t1=test01 () T2=test02 () T3=test03 ()Print('From test01 return is [%s]:'%type (t1), T1)Print('From test02 return is [%s]:'%type (t2), T2)Print('From test03 return is [%s]:'%type (t3), T3)#Output:#From test01 return is [<class ' Nonetype ';]: None#From test02 return is [<class ' int ';]: 0#From test03 return was [<class ' tuple ';]: (3, ' Hello ', [' Amy ', ' Bob '), {' name ': ' Alex ', ' age ': +})View Code
Summarize:
- Number of return values = 0: Return None
- Number of return values = 1: Return object
- Number of return values >1: return tuple
3 Function Parameters1. Formal parameters and arguments
formal parameter: Formal argument, not actual existence, is a virtual variable. Parameters are used when defining functions and function bodies, in order to receive arguments when the function is called (the number of arguments, the type should correspond to the parameter one by one).
arguments: Actual arguments, parameters that are passed to the function when the function is called, can be constants, variables, expressions, functions, and so on. Regardless of the amount of the arguments, they must have a definite value when making a function call to pass these values to the parameter. Therefore, the parameter should be determined by the method of assignment, input and so on beforehand.
The difference: The formal parameter is virtual, does not occupy the memory space, the shape parametric allocates the memory unit only when is called, at the end of the call, releases the allocated memory unit immediately. Therefore, the formal parameter is only valid inside the function. The parameter variable can no longer be used after the function call finishes returning the keynote function. An argument is a variable that consumes memory space, data is routed one-way, arguments are passed to formal parameters, and parameters are not passed to arguments.
2. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)
Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, but remember a requirement is that the key parameters must be placed after the position parameter.
def Test (x, y ): Print (x) Print (y) Test (# position parameter: Real participation formal parameter position one by one corresponds to # keyword parameter: independent of parameter position # Mixed: The keyword parameter must be placed after the position parameter #Test (y=2,1) #报错
3. Default parameters
The default parameter is not specified at the time of invocation, which is the default value, as specified by the value you specify.
Feature: When calling a function, the default parameter must not be passed.
def Test (x,y=2): Print(x) print(y) Test (# do not specify default parameters # Specifying default Parameters
4. Parameter group (non-fixed parameter)
If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter
*args: Receive 0-n positional parameters, convert narimoto Group form
def test1 (*args): print(args) test1 (# output: (1, 2, 3, 4, 5, 6) # Ibid . def test2 (x,*args): print(X,args) test2 (# output: 1 (2, 3 , 4, 5, 6)# output: 1 (), then this () is args, just because there is no value, so it is empty
**kwargs: Receive 0-n keyword parameters, converted into a dictionary form
defTest1 (* *Kwargs):Print(Kwargs) test1 (name='Alex', age=21,sex='M')#output: {' name ': ' Alex ', ' age ': +, ' sex ': ' M '}Test1 (**{'name':'Alex',' Age': 21,'Sex':'M'})#Ibid .Test1 ()#output: {}defTest2 (name,**Kwargs):Print(Name,kwargs) test2 ('Alex', age=21,sex='M')#output: Alex {' age ': +, ' sex ': ' M '}Test2 ('Alex')#output: Alex {}defTest3 (name,age=21,**Kwargs):Print(Name,age,kwargs) test3 ('Alex', sex='M', hobby='singing', age=18)#output: Alex {' sex ': ' M ', ' hobby ': ' Singing '}4 Local variables and global variablesA variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.
#variables such as strings, numbers, and so on cannot be partially modified by their valuesName ="Alex"defchange_name (name):Print("before change:", name)#AlexName ="Alex" Print(" after change", name)#Alexchange_name (name)Print(name)#Alex#variables such as lists, dictionaries, collections, classes, etc. can be modified locallynames=['Amy','Bob','Cindy']defchange_name (names):Print("before change:", names)#[' Amy ', ' Bob ', ' Cindy ']Names[0] ="Alex" Print(" after change", names)#[' Alex ', ' Bob ', ' Cindy ']change_name (names)Print(names)#[' Alex ', ' Bob ', ' Cindy ']View Code
Python3 Learning Path ~3.1 functions basic syntax and characteristics, return values, parameters, local and global variables