Initial function

First, the introduction of the function

  When we write a program, if the same function needs to be repeated 100 times.

  Without the function, we would need to copy-paste 100 times. The entire script file becomes very large.

  If we need to modify this function, then we also need to modify it 100 times. And it's error-prone. so we introduce functions.

1.1 Defining functions

  The most basic components of a function: 

      keyword def

      Function name The function name should reflect its meaning, which is the naming convention

      Comment out the code specification, explaining what the function does, and what the parameters do

      Function body The logical function that this function needs to complete.

      The return value defaults to None, which can be omitted. But we all define our own return value. Note: The function will end as soon as it encounters return, and the following code will not be executed (if else nested return).

def function name (parameter 1, parameter 2, parameter 3,...) :                    #The function name should reflect its meaning 
    ''' comment '''
    function body
    return return value#

 

1.2 The running process and calling of the function

1.2.1 Invocation

  Call: function name()         

    Step 1: Find the function name first 

    Step 2: According to the found function name, run the code saved in it

The function name is actually a variable in which the code of the function is stored. Add a () to run the code saved in it.

1.2.2 Running process  

1 x = 100
2 def add(a, b):
3     y = a + b
4     return y
5 su = add(x, 100)

  Step 1: Load x = 100 into memory.

  Step 2 : Put the function name add and its corresponding function body code in memory. Note: The code below it is not running at this time, but is just saved to the variable.

  Step 3 : Go directly to line 5. In memory, find the previous step, add the function name variable. When () is encountered, the stored code of the function variable is executed.

  Step 4 : When encountering return, return to line 5 and assign a value to su.

 

2. Function parameters

 

  

 

 

  

  

 

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324716018&siteId=291194637