The code is as follows |
Copy Code |
Def sumof (A, B): Return a + b |
1. Function parameters
The parameter name in the function is ' formal parameter ', and the value passed when calling the function is ' argument '
2. Local Variables
Variables defined within a function have nothing to do with other variables that have the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable.
Global statement that uses the global statement to assign a value to a variable outside of a function.
The code is as follows |
Copy Code |
def func (): Global X Print "x is", X x = 1 x = 3 Func () Print X #3 #1 |
3. Default parameters
Some parameters of the function can be ' optional ' by using the default parameters.
The code is as follows |
Copy Code |
Def say (msg, times = 1): Print msg * times Say ("Peter") Say ("Peter", 3) |
Note: Only those parameters at the end of the formal parameter list can have default parameter values, that is, you cannot declare a formal parameter with a default value before declaring a function parameter, and then declare a formal parameter that has no default value, only because the value assigned to the formal parameter is assigned based on the position.
4. Key parameters
If a function has many parameters, and now only wants to specify a portion of it, you can assign values (called ' key parameters ') to these parameters by name.
Pros: Don't worry about the order of the parameters, make the function simpler, and assume that the other parameters have default values, and you can assign values to only those parameters that we want.
The code is as follows |
Copy Code |
def func (A, b=2, c=3): Print ' A is%s ', B is%s, ' C is%s '% (a, B, c) Func (1) #a is 1, B are 2, C is 3 Func (1, 5) #a is 1, B are 5, C is 3 Func (1, C = ten) #a is 1, B are 2, C is 10 Func (c =, a = a) #a is, B is 2, C is 20 |
5. Return statement
Returns statements are used to return from a function, that is, to jump out of a function. You can return a value from a function.
A return statement with no returned value is equivalent to returns None. None means a special type without anything.
6. Docstrings (document String)
The code is as follows |
Copy Code |
def func (): ' This is self-defined function Doing nothing ' ' Pass Print func.__doc__ |
#This is self-defined function
#
#Do Nothing