Latest web development tutorials

Python3 function

Function is a good organization, reusable, used to achieve a single code segment, or associated functions.

Function can be applied to improve the modularity and reuse code. You already know that Python provides many built-in functions, such as print (). But you can also create your own function, which is called a user-defined function.


Define a function

You can define a function from the function you want, the following simple rules:

  • Function blockdef keyword in the beginning, followed by the function name and identifiers in parentheses ().
  • Any incoming parameters and arguments must be placed in parentheses in the middle, it can be used to define the parameters between parentheses.
  • The first line of the function statement can optionally use a string document - are used for function description.
  • Function content starting with a colon and indentation.
  • return [expression] end of the function, optionally return a value to the caller. return without an expression equivalent to return None.

grammar

Python-defined functions using def keyword, the general format is as follows:

def 函数名(参数列表):
    函数体

By default, the parameter name and parameter value is in the order defined in the function declaration matches up.

Examples

Let's use the function to output "Hello World!":

>>> def hello() :
   print("Hello World!")

   
>>> hello()
Hello World!
>>> 

Application of more complex point, to bring the function parameter variables:

#!/usr/bin/python3

# 计算面积函数
def area(width, height):
    return width * height
 
def print_welcome(name):
    print("Welcome", name)

print_welcome("w3big")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))

Examples of the above output:

Welcome w3big
width = 4  height = 5  area = 20

Function call

Define a function: to give the function a name, specify the parameters of the function contains, and code block structure.

After completion of the basic structure of this function, you can perform another function call to be executed directly from the Python command prompt.

The following examples are called printme () function:

#!/usr/bin/python3
 
# 定义函数
def printme( str ):
   "打印任何传入的字符串"
   print (str);
   return;
 
# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

Examples of the above output:

我要调用用户自定义函数!
再次调用同一函数

Parameters passed by value and pass parameters by reference

In Python, all the parameters (variables) are passed by reference. If you change a parameter in a function, then this function is called function, the original parameters are also changed. E.g:

#!/usr/bin/python3
 
# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4]);
   print ("函数内取值: ", mylist)
   return
 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print ("函数外取值: ", mylist)

And passed into the function of the object at the end to add new content using the same reference. So the output results are as follows:

函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
函数外取值:  [10, 20, 30, [1, 2, 3, 4]]

parameter

The following is the formal parameter type can be used when calling the function:

  • Required parameters
  • Keyword arguments
  • The default parameters
  • Variable-length parameters

Required parameters

Required parameters in the correct order to be passed to the function. When the number of calls and must be the same declaration.

Call printme () function, you must pass in a parameter, or syntax error will occur:

#!/usr/bin/python3
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str);
   return;
 
#调用printme函数
printme();

Examples of the above output:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    printme();
TypeError: printme() missing 1 required positional argument: 'str'

Keyword arguments

Keyword arguments and function calls a close relationship function call using keyword arguments to determine the value of the parameter passed.

When using the keyword parameter allows the function call order parameter is inconsistent with the statement, because Python interpreter capable of matching the parameter values ​​using the parameter name.

The following example function printme () is called with the parameter name:

#!/usr/bin/python3
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str);
   return;
 
#调用printme函数
printme( str = "本教程");

Examples of the above output:

本教程

The following example demonstrates the use of function parameters do not need to use the specified order:

#!/usr/bin/python3
 
#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print ("名字: ", name);
   print ("年龄: ", age);
   return;
 
#调用printinfo函数
printinfo( age=50, name="w3big" );

Examples of the above output:

名字:  w3big
年龄:  50

The default parameters

When the function is called, if the parameter is not passed, it will use the default parameters. The following example, if no incoming age parameter, the default value:

#!/usr/bin/python3
 
#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print ("名字: ", name);
   print ("年龄: ", age);
   return;
 
#调用printinfo函数
printinfo( age=50, name="w3big" );
print ("------------------------")
printinfo( name="w3big" );

Examples of the above output:

名字:  w3big
年龄:  50
------------------------
名字:  w3big
年龄:  35

Variable-length parameters

You may need a function that can handle more than the original declaration of parameters. These parameters are called the variable length parameters, and the two types of parameters are different, not naming declaration. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

With an asterisk (*) will be stored in variable names all unnamed variable parameters. If no argument when the function is called, it is an empty tuple. We can not pass unnamed variable to a function. The following examples:

#!/usr/bin/python3
 
# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   for var in vartuple:
      print (var)
   return;
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

Examples of the above output:

输出:
10
输出:
70
60
50

Anonymous function

python using lambda to create an anonymous function.

The so-called anonymous, which means no longer use this standard form def statement to define a function.

  • Just a lambda expression, the function body is much simpler than def.
  • The body is a lambda expression, rather than a block of code. We can only package a limited logic into the lambda expression.
  • lambda function has its own namespace, and can not be accessed outside of its own argument list or the global namespace parameters.
  • Although lambda function looks only write a single line, but not the same as inline functions in C or C ++, the latter purpose is not occupied when calling the small stack memory function to increase operating efficiency.

grammar

Lambda function syntax contains only one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The following examples:

#!/usr/bin/python3
 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))

Examples of the above output:

相加后的值为 :  30
相加后的值为 :  40

return statement

return [expression] statement is used to exit the function, selectively to the caller returns an expression.return statement with no parameters returns None. No previous examples demonstrate how to return a value, the following example demonstrates the use of the return statement:

#!/usr/bin/python3

# 可写函数说明
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print ("函数内 : ", total)
   return total;

# 调用sum函数
total = sum( 10, 20 );
print ("函数外 : ", total)

Examples of the above output:

函数内 :  30
函数外 :  30

Variable Scope

Pyhton, the variable is not the position in which the program can access, access depends on where the variable is assigned.

Scope of a variable determines which part of the program in which you can access a particular variable name. Two basic variable scope as follows:

  • Global Variables
  • Local variables

Global and local variables

The definition of the function of internal variables have a local scope, as defined in the outer function has global scope.

Local variables can only be declared inside a function of its access to global variables can be accessed throughout the procedures. When you call a function, all variable names in function declarations will be added to the scope. The following examples:

#!/usr/bin/python3

total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
    #返回2个参数的和."
    total = arg1 + arg2; # total在这里是局部变量.
    print ("函数内是局部变量 : ", total)
    return total;

#调用sum函数
sum( 10, 20 );
print ("函数外是全局变量 : ", total)

Examples of the above output:

函数内是局部变量 :  30
函数外是全局变量 :  0