home PYTHONJAVA
 

Python3 function

You can define a function that you want to function. Here are the simple rules:

  • The function code block begins with the def keyword followed by the function identifier name and parentheses ().
  • Any incoming parameters and parametermust be placed between the parentheses, and the parentheses can be used to define parameters.
  • The first line of the function can optionally use a docstring—for storing function descriptions.
  • The function content starts with a colon and is indented.
  • return [expression] Ends the function, optionally returning a value to the caller. A return without an expression is equivalent to returning None.

Syntax

The Python definition function uses the def keyword, which has the following general format:

def function name (parameter List):
     Function body

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

Instance

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

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

Function call

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

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

The following example calls the printme() function:

Instance (Python 3.0+)

#!/usr/bin/python3 #definition function def printme( str ): # Print any incoming strings print (str) return # calling function printme("I want to call a user-defined function!") printme("call the same function again")

Immutable types: are similar to c++ value passing, such as integers, strings, tuples. For fun(a), only the value of a is passed, which does not affect the a object itself. For example, modifying the value of a inside fun(a) simply changes another copied object without affecting a itself.

  • Variable types: are similar to c++'s reference passing, such as lists, dictionaries. For example, fun(la), the la is actually passed, and the la outside the modified fun will also be affected

  • Everything in Python is an object. Strictly speaking, we can't say value passing or reference passing. We should say passing immutable objects and passing variable objects.

    python pass immutable object instance

    Instance (Python 3.0+)

    #!/usr/bin/python3 def ChangeInt( a ): a= 10 b = 2 ChangeInt(b) print( b ) # The result is 2

    The instance has an int object 2, and the variable pointing to it is b. When passed to the ChangeInt function, the variable b is copied by value, and both a and b point to the same Int object, when a=10 , then generate an int value object 10 and let a point to it.

    Transfer variable object instance

    The mutable object modifies the argument in the function, so the original argument is also changed in the function that called the function. For example:

    Instance (Python 3.0+)

    #!/usr/bin/python3 # writable function description def changeme( mylist ): "Modify the incoming list" mylist.append([1,2,3 ,4]) print ("In-function value: ", mylist) return # Call the changeme function mylist = [10,20,30] changeme( mylist ) print ("Out-of-function value: ", mylist)

    Objects that pass in the function and add new content at the end use the same reference. Therefore, the output is as follows:

    Function value: [10, 20, 30, [1, 2, 3, 4]]
    Out-of-function value: [10, 20, 30, [1, 2, 3, 4]]

    parameter

    The following are the official 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 to the function in the correct order. The number of calls must be the same as when they were declared.

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

    Instance(Python 3.0+)

    #!/usr/bin/python3 #Writable function description def printme( str ): "Print any incoming string" print (str) return #Call the printme function printme()

    The above example output:

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

    Keyword parameter

    Keyword parameters are closely related to function calls. Function calls use keyword arguments to determine the value of the passed argument.

    Using keyword arguments allows the order of arguments to be inconsistent with the declaration time, because the Python interpreter can match parameter values with parameter names.

    The following example uses the parameter name when calling the function printme() :

    Instance (Python 3.0+)

    #!/usr/bin/python3 #writable function description def printme( str ): "Print any incoming strings " print (str) return #call printme function printme( str = "web Tutorial")

    The output of the above example:

    web Tutorial

    The following example demonstrates that the use of function parameters does not require the specified order:

    Instance (Python 3.0+)

    #!/usr/bin/python3 #writable function description def printinfo( name, age ): "Print any incoming strings " print ("Name: ", name) print ("Age: ", age) return #call printinfo function printinfo( age=50, name="welookups" )

    Default parameter

    When a function is called, if no arguments are passed, the default arguments are used. In the following example, if the age parameter is not passed, the default value is used:

    Instance (Python 3.0+)

    #!/usr/bin/python3 #writable function description def printinfo( name, age = 35 ): "Print any incoming strings " print ("Name: ", name) print ("Age: ", age) return #call printinfo function printinfo( age=50, name="welookups" ) print ("------------------------") printinfo( name="welookups" )

    The output of the above example:

    Name: welookups
    age: 50
    ------------------------
    Name: welookups
    Age: 35

    indefinite length parameter

    You may need a function that can handle more parameters than when you originally declared it. These parameters are called indefinite length parameters, which are different from the above two parameters and are not named when they are declared. The basic syntax is as follows:

    def functionname([formal_args,]  *var_args_tuple ):
       "Function_Document String"
       Function_suite
       return [ Expression]

    Parameters with an asterisk * are imported as tuples, holding all unnamed variable arguments.

    Instance (Python 3.0+)

    #!/usr/bin/python3 # writable function description def printinfo( arg1, *vartuple ): "Print any incoming parameters" print ("Output: ") print (arg1) print (vartuple) # call the printinfo function printinfo( 70, 60, 50 )

    The output of the above example:

    Output:
    70
    (60, 50)





    welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.