Define a function

Source: Internet
Author: User

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.

Grammar

The Python definition function uses the DEF keyword, and the general format is as follows:

def function name (argument list):    function Body

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

Instance

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

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

For more complex applications, the function takes a parameter variable:

#!/usr/bin/python3 #Calculate Area functiondefArea (width, height):returnWidth *Heightdefprint_welcome (name):Print("Welcome", name) print_welcome ("Runoob") W= 4h= 5Print("width ="W"height ="H"Area =", Area (W, h))#Execution ResultsWelcome runoobwidth= 4 Height = 5 Area = 20
Function call

Define a function: Give the function a name, specify the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, you can execute it through another function call or directly from the Python command prompt.

The following instance calls the printme () function:

#!/usr/bin/python3 #Defining Functionsdefprintme (str):"print any passed-in string"   Print(str)return #calling FunctionsPrintme"I want to invoke the user custom Function!") Printme ("call the same function again")#Execution ResultsI want to invoke the user custom Function! Call the same function again
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), either to a list type object, or to an S The Tring 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 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.

Python-Pass Immutable object instance
def Changeint (a):     # A = Ten  # New production variables, not formal parameters    Print (ID (a))  # if the A = 10 comment on the top, the formal parameter is printed  = 2changeint (b)print(ID (b))  #  The result is 2 .
Passing a Mutable object instance
#!/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 the object passing in the function and adding new content at the end. So the output is as follows:#Execution Resultsvalue in function: [10, 20, 30, [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.

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

#!/usr/bin/python3 #Writable Function Descriptiondefprintme (str):"print any passed-in string"   Print(str)return #Call the Printme functionPrintme ()#EXECUTE AS error resultTraceback (most recent): File"test.py", Line 10,inch<module>Printme () typeerror:printme () Missing1 Required positional argument:'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 instance uses the parameter name when the function Printme () is called:

# !/usr/bin/python3 # Writable Function Description def printme (str):    " print any passed-in string "   Print (str)    return # Call the Printme function " Beginner's Tutorial " )#  Executive Results Rookie Tutorial

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" )#Execution ResultsName: 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:

#!/usr/bin/python3 #Writable Function DescriptiondefPrintinfo (name, age = 35 ):   "print any passed-in string"   Print("Name:", name)Print("Age:", age)return #Call the Printinfo functionPrintinfo (age=50, name="Runoob" )Print("------------------------") Printinfo (name="Runoob" )#Execution ResultsName: Runoob Age:------------------------Name: Runoob Age:35
Indefinite length parameter
Https://www.cnblogs.com/xiaohei001/p/9781615.html

Define a function

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.