Python's function one

Source: Internet
Author: User

Definition of a function

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function. Functions can improve the modularity of the application, and the reuse of the code. Python provides a number of built-in functions, such as print (). You can create your own functions, which are called user-defined functions.

Rules for function definitions:

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.


def functionname (Parameters):    " Function _ Document string "    function_suite   return [expression]

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

The program code is as follows:

def   sum (x, y    ):print ('x = {0}'. Format (x    ))  Print ('y = {0}'. Format (y))    return x+  = SUM (3,10)print (m)

The results of the program run as follows:


Second, the parameters of the function

   Python can be changed (mutable) and non-changing (immutable) objects

In Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified.

Immutable type: Variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then a point to it, and 5 is discarded, not change the value of a, the equivalent of a new student into a.

Variable type: variable assignment la=[1,2,3,4] After assigning a value la[2]=5 is to change the value of the third element of List LA, itself LA is not moving, but its internal part of the value has been modified.

Parameter passing of the Python function:

Immutable types: Values such as C + + are passed, such as integers, strings, and tuples. such as fun (a), passing only a value, does not affect the A object itself. For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.

mutable types: References such as C + + are passed, such as lists, dictionaries. such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected

Everything in Python is an object, strictly meaning we can't say value passing or reference passing, we should say immutable objects and pass mutable objects.

1. Default parameters

Rules for setting default parameters:

    • The required parameter is in front, the default parameter is behind, otherwise the Python interpreter will error
    • When the function has more than one parameter, the parameter with large change is put in front, and the parameters with small change are put back. Parameters with small variations can be used as default parameters. This helps to reduce the difficulty of calling the function
    • You can provide some default parameters in order, not sequentially. When you do not provide partial default parameters in order, you need to write the parameter names
    • The default parameter must point to the immutable object

The program code is as follows:

# 1. Set a default value for the B variable # If the argument is passed in, the value of B is specified, and B overrides the passed argument, and the default value is used when B has no value def Funca (A, B = 0    ):print  a    print  bfunca (1) Funca (10,20)

The results of the program run as follows:


2. Parameter is tuple

The program code is as follows:

Print ('########### #参数为tuple ###############') def Funcd (a,b,*C):    print  (a)    print  (b)     Print " length of C is:%d " %len (c)    print  cfuncd (1, 2, 3, 4, 5, 6,)

The results of the program run as follows:

3. The parameter is Dict

The program code is as follows:

Print('############## #参数为dict ################')defFUNCF (A, * *b):Print(a)Print(b) forXinchB:PrintX +":"+str (b[x]) FUNCF (100,x='Hello', y='Hello') args= {'1':'a','2':'b'}FUNCF (100,**args)

The results of the program run as follows:


Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.

The default parameter must be used immutable object, if it is a mutable object, run there will be a logic error!

Be aware of the syntax for defining mutable parameters and keyword parameters:

*args is a variable parameter, and args receives a tuple;

**KW is the keyword parameter, and kw receives a dict.

And how to pass in the syntax for variable and keyword arguments when calling a function:

Variable parameters can be passed directly: Func (1, 2, 3), or the list or tuple can be assembled first, and then passed through *args: Func (* (1, 2, 3));

Keyword parameters can be directly passed in: Func (A=1, b=2), can be assembled dict, and then passed through **kw: func (**{' a ': 1, ' B ': 2}).

Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use the idiom

Python's function one

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.