Python3 function

A function is a well-organized, reusable piece of code that is used to implement a single, or associated function.

functions can improve the modularity of the application and the reuse of code. You already know that Python provides a lot of built-in functions, such as print(). But you can also create functions yourself, which is called a user-defined function.

Define a 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 arguments must 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:

deffunction 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!":

>>>defhello() :
print("Hello World!")
>>> hello()HelloWorld!
>>>

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.

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+)

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: