Python Learning Day7 Python3 function

Source: Internet
Author: User
Tags function definition

Python3 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. You already know that Python provides a number of 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, and here are the simple rules:

    • 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, and the parentheses can be used to define the 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.
Parameter passing

In Python, a type belongs to an object, and a variable is of no type:

a=[1,2,3]a="runoob"

In the above code,[ All-in-one] is a list type,"Runoob" is a String type, and variable A is no type, she is simply a reference to an object (a pointer), which can be a pointer to a List type object, It can also be a pointer to a String type object.

Can change (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 pass 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.

Python-Passed Immutable object instance:

# !/usr/bin/python3 def Changeint (a):     = Ten= 2changeint (b)print#  result is 2

The instance has int object 2, the variable that points to it is B, and when passed to the Changeint function, the variable b,a and B both point to the same int object, and at a=10, the new int value Object 10, and a points to it.

To pass a Mutable object instance:

A mutable object modifies a parameter in a function, and the original parameter is changed in the function that calls the function. For example:

#!/usr/bin/python3 #Writable Function Descriptiondefchangeme (mylist):"to modify an incoming list"Mylist.append ([1,2,3,4]); Print("value in function:", MyList)return #Call the Changeme functionMyList = [10,20,30];changeme (mylist);Print("values outside the function:", MyList)

The same reference is used for an object that passes in the function and adds new content at the end. So the output is as follows:

function values:  [1, 2, 3, 4]] outside the function:  [10, 20, 30, [1, 2, 3, 4]]
Parameters

The following are the formal parameter types that can be used when calling a function:

    • Required Parameters
    • Keyword parameters
    • Default parameters
    • Indefinite length parameter
Required Parameters

Required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

If you call the Printme () function, you must pass in a parameter, or a syntax error will occur:

# !/usr/bin/python3 # Writable Function Description def printme (str):    " print any passed-in string "   Print (str);    return  # Call the Printme function printme ();

The result of the above example output:

Traceback (most recent):   " test.py "  in <module>    'str'
Keyword parameters

Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.

Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

The following example shows that the use of function parameters does not need to use the specified order:

#!/usr/bin/python3 #Writable Function DescriptiondefPrintinfo (name, age):"print any passed-in string"   Print("Name:", name); Print("Age:", age); return; #Call the Printinfo functionPrintinfo (age=50, name="Runoob");

The result of the above example output:

Name:  runoob Age:  50
Default parameters

When a function is called, default parameters are used if no arguments are passed. The default value is used if the age parameter is not passed in the following instance:

def printinfo (name, age=35):    print ("", name);     Print ("", age);     return ;p rintinfo ('Alex')

Output Result:

Name:  Alex Age:  35
Inheritance of default values for parameters
#!/usr/bin/env python#-*-coding:utf-8-*-classdemo_list:def __init__(Self, l=[]):        Print(ID (l), x="') SELF.L=LdefAdd (Self, ele): Self.l.append (ele)defAppender (ele): obj=demo_list () obj.add (ele)PrintOBJ.Lif __name__=="__main__":     forIinchRange (5): Appender (i)

The output is:

4346933688 [0]
4346933688 [0, 1]
4346933688 [0, 1, 2]
4346933688 [0, 1, 2, 3]
4346933688 [0, 1, 2, 3, 4]

It is clear that each time the __init__ function is called, the default parameter L is the same object with an ID of 4346933688.

With regard to the default parameters, this is said in the document:

Functions in Python is first-class objects, and not only a piece of code.

We can read this: The function is also an object, so the definition is executed, the default argument is the function's property, and its value may change as the function is called . Aren't all the other objects so?

Parameters with *: Used to accept variable quantity parameters

So far, when we're defining a function, we have to pre-define how many arguments (or how many arguments can be accepted) the function needs. In general, this is fine, but there is also the case when defining a function that does not know the number of arguments (think of the printf function in c), in Python, the parameter with * is used to accept a variable number of parameters. See an example:

def Funcd (A, B, *c):  print(a)  print(b)    Print("" % len (c))  print(c) FUNCD ( 1,2,3,4,5,6)

Results:

is: 4 (3, 4, 5, 6)

As we can see, the first two parameters are accepted by a, B, and the remaining 4 parameters are all accepted by C, and C is a tuple here. When we call FUNCD, we have to pass at least 2 parameters, 2 or more parameters, put in C, if there are only two parameters, then C is an empty tuple.

func (*args)The passed in parameter is in the form of a tuple in args
def F (*args):    print(args)    print(type (args)) F ( (+/-) F (#  This way you can directly use all the elements of a list as indeterminate arguments

Results:

(1, 2, 3)<class'tuple'>(4, 5, 6) <class'tuple'>
func (**kwargs)The passed in parameter is in the form of a dictionary in args
def F (* *args)    :print(args    )print(type (args)) f (a=1 , b=2,c=3) F (**{'d': 4,'e': 5,'  F'#  This way you can directly pass in all the key values of a dictionary as a keyword argument

Results:

{'a': 1,'b': 2,'C': 3}<class 'Dict'>{'D': 4,'e': 5,'F': 6}<class 'Dict'>
func (*args, **kwargs)

The order of incoming must be the same as the order of the definition, here is the indefinite parameter list, and then the keyword parameter dictionary, such as:

Parameters with * *:

If the last formal parameter in a function definition has a * * (double star) prefix , all other keyword parameters other than the normal parameter will be placed in a dictionary passed to the function , such as:

def FUNCF (A, * *b)  :print(a  )for in b    : Print "  " + str (b[x])) FUNCF (c=' hello ', b=200)

Results:

200

As you can see,B is a Dict object instance that accepts the keyword arguments B and c.

The most essential meanings of * and * *:

In Python functions, we have to pay attention to two features, one on the keyword parameters, and one is arbitrary parameters. The essential meaning of arbitrary parameters is to allow the function to accept any number of parameters , its essential meaning is to use *args to represent a set , and when this parameter is assigned, it will receive as much as possible the parameters it can accept to form a set.

That is, in fact, assuming that the function's formal parameter is corresponding to the number of arguments, and the introduction of *args, which represents *args, represents 0 to any number of parameters. Similarly **args (he is a dictionary collection).

Python Learning Day7 Python3 function

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: info-contact@alibabacloud.com 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.