The content of this article is the basic knowledge of Python function, now share to everyone, the need for small partners can refer to the content of the article
Function: If you need a block of code multiple times when developing a program, but in order to improve the efficiency of writing and the reuse of code, the code block with independent function is organized into a small module
This is the function.
function definition and invocation
<1> defining functions
The format of the definition function is as follows:
def function name ():
Code
<2> calling functions
Once a function is defined, it is equivalent to having a code with some functionality that you want to be able to execute and call it
The calling function is simple, with the function name () to complete the call
function parameters (i)
In order to make a function more general, that is, to let it calculate which two number of the and, let it calculate which two number of the and, when defining the function can let the function to receive data,
This solves the problem, which is the parameter of the function.
<1> defining a function with parameters
Examples are as follows:
Def add2num (A, B):
c = a+b
Print C
<2> calling a function with parameters
To invoke the Add2num (a, B) function above, for example:
Def add2num (A, B):
c = a+b
Print C
Add2num (one, all) #调用带有参数的函数时, you need to pass the data in parentheses
<4> Small Summary
A parameter in parentheses that is used to receive arguments, called "Formal parameters".
Arguments in parentheses that are used to pass to the function, called "arguments"
function return value (i)
<1> "Return value" Introduction
The so-called "return value", that is, the function of the program to complete one thing, and finally to the caller's results
<2> functions with return values
To return the result to the caller in the function, you need to use return in the function
The following example:
Def add2num (A, B):
c = a+b
Return C
Or
Def add2num (A, B):
Return a+b
<3> save return value of function
At the beginning of this section, the "Buy cigarettes" example, when the last son gave you a cigarette, you must have taken it from your son, right, the procedure is the same, if a function returns a data, then want to use this data, then you need to save
An example of the return value of a Save function is as follows:
#定义函数
Def add2num (A, B):
Return a+b
#调用函数, by the way, save the return value of the function
result = Add2num (100,98)
#因为result已经保存了add2num的返回值, so you can use it next
Print result
Results:
198
function return value (ii)
Could we return multiple values in Python?
>>> def pid (A, B):
... shang = a//b
... Yushu = a%b
... return Shang, Yushu
...
>>> sh, yu = pid (5, 2)
>>> SH
5
>>> Yu
1
The essence is the use of tuples
4 Types of functions
function According to whether there are parameters, there is no return value, can be combined with each other, a total of 4
No parameter, no return value
No parameters, and return
With parameters, no return value
With parameters, with return values
<1> function without parameters, no return value
Such functions, which cannot receive parameters, nor return values, are normally printed with a function similar to the indicator light, using such functions
<2> functions with no parameters and return values
This kind of function, cannot receive the parameter, but can return some data, generally, like collects the data, uses this kind of function
# Get the temperature
Def gettemperature ():
#这里是获取温度的一些处理过程
#为了简单起见, the first simulation returns a data
Return 24
Temperature = Gettemperature ()
Print (' Current temp:%d '%temperature)
Results:
The current temperature is: 24
<3> functions with parameters and no return values
Such functions, can receive parameters, but can not return data, in general, set the data for some variables without the result, use such functions
<4> functions with parameters and return values
Such functions, not only to receive parameters, but also to return some data, in general, such as data processing and require the results of the application, with such functions
# calculates the accumulation of 1~num and
def calculatenum (num):
result = 0
i = 1
While I<=num:
result = result + I
I+=1
return result
result = Calculatenum (100)
Print (' 1~100 cumulative and is:%d '%result)
Results:
1~100 cumulative and is: 5050
function parameters (ii)
1. Default parameters
When a function is called, the value of the default parameter is considered to be the default value if it is not passed in. The following example prints the default age if age is not passed in:
def printinfo (name, age = 35):
# Print any incoming string
Print "Name:", name
print ' age ', age
# Call the Printinfo function
Printinfo (name= "Miki")
Printinfo (age=9,name= "Miki")
The result of the above example output:
Name:miki
Age 35
Name:miki
Age 9
Note: Parameters with default values must be in the last face of the parameter list.
>>> def printinfo (name, age=35, sex):
... print Name
...
File "<stdin>", line 1
Syntaxerror:non-default argument follows default argument
2. Indefinite length parameter
Sometimes a function may be required to handle more arguments than was originally declared. These parameters are called variable length parameters and are not named when declared.
The basic syntax is as follows:
def functionname ([Formal_args,] *args, **kwargs):
"Function _ Document String"
Function_suite
return [expression]
A variable with an asterisk (*) will hold all unnamed variable arguments, and args is a tuple, while the Kwargs variable will hold the named argument.
That is, as the Key=value parameter, Kwargs is a dictionary.
>>> def fun (A, B, *args, **kwargs):
... "" "Variable parameter demo example" "
... print "a =", a
... print "b =", b
... print "args =", args
... print "Kwargs:"
... for key, value in Kwargs.items ():
... print key, "=", value
...
>>> Fun (1, 2, 3, 4, 5, m=6, n=7, p=8) # Note the parameters that are passed
A = 1
b = 2
args = (3, 4, 5)
Kwargs:
p = 8
m = 6
n = 7
>>>
>>>
>>>
>>> C = (3, 4, 5)
>>> d = {"M": 6, "n": 7, "P": 8}
>>> Fun (1, 2, *c, **d) # Note how tuples and dictionaries are passed
A = 1
b = 2
args = (3, 4, 5)
Kwargs:
p = 8
m = 6
n = 7
>>>
>>>
>>>
>>> Fun (1, 2, C, D) # Note the difference between the asterisk and the above
A = 1
b = 2
args = ((3, 4, 5), {' P ': 8, ' m ': 6, ' n ': 7})
Kwargs:
>>>
>>>
3. Referring to the parameters
What is the difference between a mutable type and a variable of an immutable type as a function parameter?
Does Python have a pointer to a language similar to C?
>>> def Selfadd (a):
... "" "Increase" ""
... A + = a
...
>>> A_int = 1
>>> A_int
1
>>> Selfadd (A_int)
>>> A_int
1
>>> a_list = [1, 2]
>>> a_list
[1, 2]
>>> Selfadd (a_list)
>>> a_list
[1, 2, 1, 2]
The function parameter in Python is a reference pass (note that it is not a value pass). For an immutable type, the dependent variable cannot be modified, so the operation does not affect the variable itself
, and for a mutable type, an operation in the body of a function might change an incoming parameter variable.
Nested calls to functions
Def TESTB ():
Print ('----testb start----')
Print (' Here is the code executed by the TESTB function ')
Print ('----testb end----')
Def TestA ():
Print ('----testA start----')
TESTB ()
Print ('----testA end----')
TestA ()
Results:
----TestA Start----
----TESTB Start----
Here is the code that the TESTB function executes
----TESTB End----
----TestA End----
Think & Implement 1
Write a function to print a horizontal line
Print a horizontal line of custom lines
Reference Code 1
# Print a horizontal line
Def printoneline ():
Print ("-" *30)
# Print multiple horizontal lines
def printnumline (num):
I=0
# because the Printoneline function has finished printing the horizontal line function,
# Just call this function multiple times to
While I<num:
Printoneline ()
I+=1
Printnumline (3)
Think & Implement 2
Write a function to ask for three numbers and
Write a function to find an average of three numbers
Reference Code 2
# ask for 3 numbers and
def sum3number (a,b,c):
Return A+b+c # return can be followed by a number, but also an expression
# Complete the averaging of 3 numbers
def average3number (a,b,c):
# because the Sum3number function has completed 3 numbers on the same, so just call to
# that is, the received 3 number, as an argument to pass
Sumresult = Sum3number (a,b,c)
Averesult = sumresult/3.0
Return Averesult
# Call function, finish averaging 3 numbers
result = Average3number (11,2,55)
Print ("Average is%d"%result)
Local variables
A local variable, which is a variable defined inside a function
Different functions can define local variables of the same name, but each one does not have an effect
The role of local variables, in order to temporarily save the data need to define variables in the function to be stored, which is its role
Global variables
A variable is a global variable if it can be used in a function or in another function.
The demo is as follows:
# define Global Variables
A = 100
def test1 ():
Print (a)
Def test2 ():
Print (a)
# Call function
Test1 ()
Test2 ()
Variables defined outside the function are called global variables
Global variables can be accessed in all functions
If you modify a global variable in a function, you need to declare it using global, otherwise an error
If the name of the global variable and the name of the local variable are the same, then the use of local variables, small tips strong dragon pressure local bully
Recursive functions
If a function does not invoke other functions internally, but itself, the function is a recursive function.
For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n
def calnum (num):
i = 1
return = 1
While I<=num:
return *= I
I+=1
return result
ret = Calnum (3)
Print (ret)
anonymous functions
Use lambda keywords to create small anonymous functions. This function is named after the standard procedure for declaring a function with DEF is omitted.
The syntax for a lambda function contains only one statement, as follows:
Lambda [arg1 [, Arg2,..... argn]]:expression
The following example:
sum = lambda arg1, arg2:arg1 + arg2
#调用sum函数
Print "Value of total:", sum (10, 20)
Print "Value of total:", sum (20, 20)
The result of the above example output:
Value of Total:30
Value of Total:40
A lambda function can receive any number of arguments but only return the value of an expression
Anonymous functions cannot call print directly, because lambda requires an expression
Application situations
function as a parameter pass
Define your own functions
>>> def fun (A, B, opt):
... print "a =", a
... print "b =", b
... print "result =", opt (A, B)
...
>>> Fun (1, 2, Lambda x,y:x+y)
A = 1
b = 2
result = 3
Parameters as built-in functions
Think about how the following data specifies the sort by age or name?
Stus = [
{"Name": "Zhangsan", "Age": 18},
{"Name": "Lisi", "Age": 19},
{"Name": "Wangwu", "Age": 17}
]
Sort by name:
>>> stus.sort (key = lambda x:x[' name ')
>>> Stus
[{' Age ': +, ' name ': ' Lisi '}, {' Age ': +, ' name ': ' Wangwu '}, {' Age ': ', ' name ': ' Zhangsan '}]
Sort by age:
>>> stus.sort (key = lambda x:x[' age ')
>>> Stus
[{' Age ': +, ' name ': ' Wangwu '}, {' Age ': ' + ', ' name ': ' Zhangsan '}, {' Age ': +, ' name ': ' Lisi '}]
Function Usage Considerations
1. Custom Functions
<1> no parameter, no return value
def function name ():
Statement
<2> no parameters, with return values
def function name ():
Statement
Return the value that needs to be returned
Attention:
If a function has no return value, see if there is return, because only return returns the data.
In development, it is often necessary to design functions according to requirements without the need to return values
function, you can have multiple return statements, but as long as a return statement is executed, it means that the function's call is complete
<3> parameter, no return value
def function name (formal parameter list):
Statement
Attention:
When calling a function, if you need to pass some data together in the past, the called function needs to use parameters to receive
The number of variables in the argument list is determined based on how much data is actually passed
<4> with parameters, return values
def function name (formal parameter list):
Statement
Return the value that needs to be returned
<5> function names cannot be duplicated
2. Calling functions
The <1> is called in the following way:
function name ([argument list])
<2> when it is called, the writer does not write realistic arguments
If the called function is defined with a physical parameter, then the argument should be passed at the time of the call
<3> when called, the number and order of arguments should be consistent with the requirements in the definition function
<4> if the called function has a return value, then a variable can be used to save the value
3. Scope
<1> variables defined in a function can only be used in this function (local variables)
<2> variables defined outside the function that can be used in all functions (global variables)
Related recommendations:
Introduction to Python basic functions