Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python function


May 10, 2021 Python2


Table of contents


Python function

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.


Define a function

You can define a function that you want to function from, and here are the simple rules:

  • The function block begins with the def keyword, followed by the function identifier name and parentheses ().
  • Any incoming arguments and arguments must be placed in the middle of the parenthesis. Between parentheses can be used to define parameters.
  • The first line statement of the function selectively uses the document string -- used to hold the function description.
  • The contents of the function start with a colon and are indented.
  • Return(expression) ends the function and selectively returns a value to the caller. Return without an expression is equivalent to returning None.

Grammar

def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]

By default, parameter values and parameter names are matched in the order defined in the function declaration.

Instance

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

The function is called

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:

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

The argument is passed

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.

Changeable (mutable) and non-changeable (immutable) objects

In Python, strings, tuples, and numbers are non-changeable objects, while lists, dicts, and so on are objects that can be modified.

  • Immvable type: The variable assigns a-5 and then assigns a-10, where a new int value object is actually generated, and then a points to it, and 5 is discarded, not changing the value of a, which is equivalent to a new one.
  • Variable type: Variable assignment la, 1, 2, 3, 4, and then assign la, 2, 5, changes the value of the third element of list la, which itself la does not move, but only a portion of its internal value is modified.

The arguments of the Python function are passed:

  • Immedible type: Value passes like c+, such as integers, strings, and yuans. F or example, fun(a), only the value of a is passed and does not affect the a object itself. For example, modifying the value of a within fun(a) only another copied object does not affect a itself.
  • Variable type: A reference pass, such as a list, a dictionary, similar to c+ If fun(la) is passed on to the past, the la outside of the modified fun will also be affected

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.

Python passed on immedible object instances

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.

Pass parameters by value and pass parameters by reference (pass variable object instances)

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]]

Parameters

Here are the types of formal parameters that can be used when calling functions:

  • The required parameters
  • Name the parameters
  • The default parameter
  • Indefinite long parameters

The required parameters

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

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

The default parameter

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

Indefinite long parameters

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

Anonymous function

python uses lambda to create anonymous functions.

  • Lambda is just an expression, and the function body is much simpler than def.
  • Lambda's body is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.
  • Lambda functions have their own namespaces and cannot access parameters outside their own list of parameters or in the global namespace.
  • Although lambda functions appear to write only one line, they are not the same as inline functions in C or C+, which are designed to increase operational efficiency by calling small functions without taking up stack memory.

Grammar

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

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

Variable scope

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:

  • Global variable
  • The local variable

Variables and local variables

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