May 10, 2021 Python2
Functions are encapsulated, reusable snipper used to implement a single, or associated function.
Functions can improve the modularity of the application and the reusability of the code. A s you already know, Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
You can define a function that you want to function from, and here are the simple rules:
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
By default, parameter values and parameter names are matched in the order defined in the function declaration.
Below is a simple Python function that uses a string as an incoming argument and then prints it to a standard display device.
def printme( str ):
"打印传入的字符串到标准显示设备上"
print str
return
Defining a function gives only one name to the function, specifying the parameters contained in the function, and the structure of the block of code.
Once the basic structure of the function is complete, you can call execution from another function or directly from the Python prompt.
The printme() function is called by the following instance:
#coding=utf-8
#!/usr/bin/python
# Function definition is here
def printme( str ):
"打印任何传入的字符串"
print str;
return;
# Now you can call printme function
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");
The above example output results:
我要调用用户自定义函数!
再次调用同一函数
In Python, the type belongs to the object, and the variable is not:
a=[1,2,3]
a="w3cschool"
In the above code, the list type, "w3cschool" is the string type, and the variable a is no type, she is just a reference to an object (a pointer), can be a list type object, or point to a string type object.
In Python, strings, tuples, and numbers are non-changeable objects, while lists, dicts, and so on are objects that can be modified.
The arguments of the Python function are passed:
Everything in Python is an object, strictly meaning we can't say value pass or reference pass, we should say pass immedible object and pass variable object.
Example (Python 2.0 plus)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def ChangeInt( a ):
a = 10
b = 2
ChangeInt(b)
print b # 结果是 2
There is an int object 2 in the instance, the variable pointing to it is b, and when passed to the ChangeInt function, the variables b, a and b are copied as passed values point to the same int object, and at a=10, a new int value object 10 is generated and a points to it.
All parameters (arguments) are passed by reference in Python. I f you modify an argument in a function, the original argument is also changed in the function that calls the function. For example:
#coding=utf-8
#!/usr/bin/python
# 可写函数说明
def changeme( mylist ):
"修改传入的列表"
mylist.append([1,2,3,4]);
print "函数内取值: ", mylist
return
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist
Objects that pass in functions and add new content at the end use the same reference. Therefore, the output results are as follows:
函数内取值: [10, 20, 30, [1, 2, 3, 4]]
函数外取值: [10, 20, 30, [1, 2, 3, 4]]
Here are the types of formal parameters that can be used when calling functions:
The necessary parameters must be passed in the function in the correct order. The number at the time of the call must be the same as at the time of the declaration.
To call the printme() function, you must pass in an argument or you will get a syntax error:
#coding=utf-8
#!/usr/bin/python
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print str;
return;
#调用printme函数
printme();
The above example output results:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword parameters are closely related to function calls, which use keyword parameters to determine the value of incoming parameters.
Use keyword parameters to allow the order of parameters when a function is called to be inconsistent with when declared, because the Python interpreter can match parameter values with parameter names.
The following instance uses the argument name when the function printme() is called:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print str;
return;
#调用printme函数
printme( str = "My string");
The above example output results:
My string
The following example shows that the order of keyword parameters is less important:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#可写函数说明
def printinfo( name, age ):
"打印任何传入的字符串"
print "Name: ", name;
print "Age ", age;
return;
#调用printinfo函数
printinfo( age=50, name="miki" );
The above example output results:
Name: miki
Age 50
Name the parameters
Named arguments are closely related to function calls, and callers use the names of arguments to determine the value of incoming arguments. Y ou can skip unthirded parameters or garbled parameters because the Python interpreter can match parameter values with parameter names. Call the printme() function with a named argument:
#coding=utf-8
#!/usr/bin/python
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print str;
return;
#调用printme函数
printme( str = "My string");
The above example output results:
My string
The following example shows that the order of named parameters is less important:
#coding=utf-8
#!/usr/bin/python
#可写函数说明
def printinfo( name, age ):
"打印任何传入的字符串"
print "Name: ", name;
print "Age ", age;
return;
#调用printinfo函数
printinfo( age=50, name="miki" );
The above example output results:
Name: miki
Age 50
When a function is called, the value of the default argument is considered the default if it is not passed in. The following example prints the default age if age is not passed in:
#coding=utf-8
#!/usr/bin/python
#可写函数说明
def printinfo( name, age = 35 ):
"打印任何传入的字符串"
print "Name: ", name;
print "Age ", age;
return;
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );
The above example output results:
Name: miki
Age 50
Name: miki
Age 35
You may need a function that can handle more arguments than when you originally declared them. T hese parameters are called indetermensitive long parameters and, like the two parameters above, are not named when declared. The basic syntax is as follows:
def functionname([formal_args,] *var_args_tuple ):
"函数_文档字符串"
function_suite
return [expression]
The variable name with the asterisk (*) holds all the unnamed variable parameters. I t is also available to select not many pass parameters. Here's an example:
#coding=utf-8
#!/usr/bin/python
# 可写函数说明
def printinfo( arg1, *vartuple ):
"打印任何传入的参数"
print "输出: "
print arg1
for var in vartuple:
print var
return;
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );
The above example output results:
输出:
10
输出:
70
60
50
python uses lambda to create anonymous functions.
The syntax of the lambda function contains only one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
Here's an example:
#coding=utf-8
#!/usr/bin/python
#可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
#调用sum函数
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
The above example output results:
Value of total : 30
Value of total : 40
The return statement exits the function and selectively returns an expression to the caller. T he return statement without parameter value returns None. None of the previous examples show how to return values, and the following example tells you how to do it:
#coding=utf-8
#!/usr/bin/python
# 可写函数说明
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# 调用sum函数
total = sum( 10, 20 );
print "Outside the function : ", total
The above example output results:
Inside the function : 30
Outside the function : 30
Not all variables of a program are accessible anywhere. Access is determined by where the variable is assigned.
The scope of a variable determines which part of the program you can access to which particular variable name. The two most basic variable scopes are as follows:
A variable that defines inside a function has a local scope, and a variable that defines a global scope outside the function.
Local variables can only be accessed within their declared functions, while global variables can be accessed throughout the program. W hen a function is called, all variable names declared within the function are added to the scope. Here's an example:
#coding=utf-8
#!/usr/bin/python
total = 0; # This is global variable.
# 可写函数说明
def sum( arg1, arg2 ):
#返回2个参数的和."
total = arg1 + arg2; # total在这里是局部变量.
print "Inside the function local total : ", total
return total;
#调用sum函数
sum( 10, 20 );
print "Outside the function global total : ", total
The above example output results:
Inside the function local total : 30
Outside the function global total : 0