Python System Study Notes (3) --- function

Source: Internet
Author: User

Functions: 1. When a function is used, statements in a Python program are organized into functions. In layman's terms, a function is a statement group that completes a specific function. This group of statements can be used as a unit and given a name to it. In this way, we can execute the function name multiple times in different places of the Program (this is usually called a function call), but do not need to write these statements repeatedly in all places. In addition, each time you use a function, you can provide different parameters as input to process different data. After the function is processed, you can also feedback the corresponding results to us. Some functions are compiled by the user, which is usually called user-defined functions. In addition, the system also comes with some functions, and some third-party functions, such as some functions compiled by other programmers, we call it a pre-defined Python function, which can be used directly by users of these ready-made functions. Ii. Why do we use functions mainly for two reasons: first, to reduce programming difficulty, A complex big problem is usually divided into a series of simpler small problems, and then the small problem is further divided into smaller problems. When the problem is refined into simple enough, we can divide and conquer it. At this time, we can use functions to deal with specific problems. Once small problems are solved, the major problems will be solved. Second, code reuse. The defined functions can be used in multiple locations of a program, or in multiple programs. In addition, we can put functions in a module for other programmers to use. At the same time, we can also use functions defined by other programmers. This avoids repetitive work and provides work efficiency. Basic syntax def fun (n, m ,...)............ (return n) for return1, return can have, can have, 2, no return method returns None, 3, return is also returned if there is no expression after return, 4, if the function cannot reach the end, None is returned. With regard to variables and method 1, the method name defined will be registered in the "current symbol table", so that the system will know that this method is named a method and assign a method to a variable, this variable becomes the corresponding method. 2. Each level has its own symbol table, which is the same as the program level we learned previously. The inner symbol table can use the content in the outer symbol table, but it is no longer a level, so it has nothing to do with it. It means that the upper layer can only communicate with the lower layer through parameters, the upper layer of the lower layer can only return values. Till now, we only know that there is a value transfer. That is to say, the function has nothing to do with the external. 3. That is to say, up to now, there is no relationship between the function layer and the upper layer. It has its own symbol table. parameters can only get values from the upper layer, but cannot change the content of the upper layer, all variables used inside the function are independent of the upper layer of the function itself. That is to say, the function basically cannot change the upper layer. A function is a reusable program segment. They allow you to give a statement a name, and then you can use this name to run the statement block multiple times anywhere in your program. This is called a function. We have used many built-in functions, such as len and range. The function is defined by the def keyword. The def keyword is followed by the identifier name of a function, followed by a pair of parentheses. Variable names can be included in parentheses, which end with a colon. Next is a statement, which is the function body. 1. Define a function: for example, [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: function1.py def sayHello (): print ('Hello World! ') # Block belonging to the function # End of function sayHello () # call the function again </span> output: C: \ Users \ Administrator> python D: \ python \ function1.pyHello World! Hello World! Working principle: we use the syntax described above to define a function called sayHello. This function does not use any parameters, so no variables are declared in parentheses. For a function, parameters are only input to the function, so that we can pass different values to the function and get the corresponding results. We called the same function twice in the program to avoid writing the same program segment twice. 2. function parameters: the parameters obtained by the function are the values you provide to the function, so that the function can use these values to do something. These parameters are just like variables, except that their values are defined when we call a function, rather than being assigned values in the function itself. The parameter is specified in the parentheses defined by the function and is separated by commas. When we call a function, we provide the value in the same way. Note the term we used-the parameter name in the function is the form parameter and the value you provide to the function call is called the real parameter. Use function parameters: for example, [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_param.py def printMax (a, B): if a> B: print (a, 'is maximum') elif a = B: print (a, 'is equal to', B) else: print (B, 'is maximum') printMax (3, 4) # directly give literal values x = 5 y = 7 printMax (x, y) # give variables as arguments </span> output: c: \ Users \ Administrator> python D: \ python \ func_param.py4 is maxi Mum 7 is maximum working principle: Here, we define a function called printMax, which requires two parameters, a and B. We use the if... else statement to find a large number of the two and print a large number. In the use of the first printMax, we directly provide the number, that is, the real parameter, to the function. In the second use, we use variables to call functions. PrintMax (x, y) assigns the value of real parameter x to the form parameter a, and the value of real parameter y to the form parameter B. In the two calls, the printMax function works exactly the same. 3. Local variables: When you declare variables in the function definition, they have no relationship with other variables with the same name outside the function, that is, the variable name is local for the function. This is called the scope of a variable. The scope of all variables is the block they are defined, starting from the point where their names are defined. For example: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_local.py x = 50 def func (x ): print ('x is ', x) x = 2 print ('changed local x to', x) func (x) print ('x is still', x) </span> output: C: \ Users \ Administrator> python D: \ python \ func_local.pyx is 50 Changed local x to 2 x is still 50 working principle: In the function, when we use the value of x for the first time, Python uses the value of the form parameter declared by the function. Next, we assign value 2 to x. X is the local variable of the function. Therefore, when we change the value of x in the function, the x defined in the main block is not affected. In the last print statement, we prove that the value of x in the main block is indeed not affected. 4. global variables: If you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local but global. We use the global statement to complete this function. Without a global statement, it is impossible to assign values to variables defined outside the function. You can use the value defined outside the function (assuming there is no variable with the same name in the function ). However, this is not recommended, and we should avoid it as much as possible, because it makes the reader of the program unclear where the variable is defined. The global statement clearly indicates that the variable is defined in the block outside. We can use [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_global.py x = 50 def func (): global x print ('x is ', x) x = 2 print ('changed global x to', x) func () print ('value of x is ', x) </span> output: C: \ Users \ Administrator> python D: \ python \ func_global.pyx is 50 Changed global x to 2 Value of x is 2 Working principle: the global statement is used to declare that x is global. Therefore, when we assign the value to x in the function, this change is also reflected when we use the value of x in the main block. You can use the same global statement to specify multiple global variables. For example, global x, y, and z. 5. external variables: we already know how to use local variables and global variables, and an external variable is between the above two variables. When we declare external variables in the function, they are visible in the function. Since everything is executable code in python, you can define a function at any position, as in the following example, func_inner () is defined in func_outer. The following example shows how to use an external variable: [python <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_nonlocal.py def func_outer (): x = 2 print ('x is ', x) def func_inner (): nonlocal x = 5 func_inner () print ('changed local x to', x) func_outer () </span> output: C: \ Users \ Administrator> python D: \ python \ func_nonlocal.pyx is 2 Changed local x to 5 Working principle: when we are in the func_inner () function, the variable x defined in the first row of the function func_outer () is neither an internal variable nor Func_inner block) is not a global variable (it is not included in the main program block). In this case, we use nonlocal x to declare that we need to use this variable. You can try to change the declaration method and then observe the differences between these variables. 6. default parameter values for some functions, you may want some of their parameters to be optional. If you do not want to provide values for these parameters, these parameters use the default values. This function is completed by default parameter values. You can add the value assignment operator (=) and default value after the parameter name defined by the function to specify the default parameter value for the parameter. Note that the default parameter value is a constant. More accurately, the default parameter value should be immutable. Use the default parameter value: for example, [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_default.py def say (message, times = 1): print (message * times) say ('hello') say ('World', 5) </span> output: C: \ Users \ Administrator> python D: \ python \ func_default.pyHello WorldWorldWorldWorldWorld Working principle: the function named "say" is used to print any number of times a string needs. If we do not provide a value, the string will be printed only once by default. This function is implemented by specifying the default value of 1 for the parameter times. When we use say for the first time, we only provide one string, and the function only prints the string once. When we use say for the second time, we provide the string and parameter 5, indicating that we want to print the string message five times. Note: Only those parameters at the end of the parameter table can have default parameter values. That is, you cannot declare a parameter with the default value when declaring a function parameter, and then declare a parameter without the default value. This is because the value assigned to the form parameter is assigned based on the position. For example, def func (a, B = 5) is valid, but def func (a = 5, B) is invalid. 7. Keyword (Keyword) parameters: If a function has many parameters and you only want to specify a part of them, then you can assign values to these parameters by name. This is called a keyword parameter. We use the name (keyword) instead of the position (the method we have been using) to specify real parameters for the function. This method has two advantages: 1. Since we do not have to worry about the order of parameters, it is easier to use functions. 2. If other parameters have default values, we can assign values to only the parameters we want. Key parameters: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_key.py def func (a, B = 5, c = 10): print ('A is ', a,' and B is ', B,' and c is ', c) func (3, 7) func (25, c = 24) func (c = 50, a = 100) </span> output: C: \ Users \ Administrator> python D: \ python \ func_key.pya is 3 and B is 7 and c is 10 a is 25 and B is 5 and c is 24 a is 100 and B is 5 and c is 50 working principle: A function named func has a parameter without default values and two parameters with default values. Number. When the function is used for the first time, func (3, 7), parameter a gets the value 3, parameter B gets the value 7, and parameter c uses the default value 10. When the second function func (25, c = 24) is used, value 25 is obtained based on the location variable a of the real parameter. According to the name, that is, the key parameter, the value of parameter c is 24. Variable B is 5 by default. When using func (c = 50, a = 100) for the third time, we use key parameters to completely specify the parameter value. Note: Although function definition defines a before c, we can still specify the value of parameter c before. 8. VarArgs parameters: Sometimes you may want to define a function that can accept any number of parameters. You can use asterisks to complete the function. For example: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: total. py def total (initial = 5, * numbers, ** keywords): count = initial for number in numbers: count + = number for key in keywords: count + = keywords [key] return count print (total (10, 1, 2, 3, vegetables = 50, fruits = 100) </span> output: C: \ Users \ Administrator> python D: \ python \ total. py166 Working principle: When we declare a form parameter with a star number, such as * param, the real parameter from this position to the end Will be collected in the 'param' Meta Group. Similarly, when we declare a parameter as a binary star, for example, ** param, the real parameters from this position to the end will be collected in a dictionary named 'param. The tuples and dictionaries are described in detail later. 9. Keyword-only parameter: if we want some key parameters to be obtained only by the real parameter rather than by location, we can declare them behind the asterisk parameter. For example: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;"> # Filename: keyword_only.py def total (initial = 5, * numbers, extra_number): count = initial for number in numbers: count + = number count + = extra_number print (count) total (10, 1, 2, 3, extra_number = 50) total (10, 1, 2, 3) # Raises error because we have not supplied a default argument value for 'extra _ number' </span> output: C: \ Users \ Admi Nistrator> python D: \ python \ keyword_only.py66 Traceback (most recent call last): File "D: \ python \ keyword_only.py", line 11, in <module> total (10, 1, 2, 3) TypeError: total () needs keyword-only argument extra_number Working principle: the formation of the declaration after the asterisk form parameter becomes a keyword limit parameter. If you do not provide a default value for these arguments, you must assign a value to the arguments using the keyword when calling the function. Otherwise, an error is thrown, as shown in the preceding example. Note that the x + = y used here is equivalent to x = x + y. If you do not need asterisks, You can omit the parameter names of asterisks, such as total (initial = 5, *, extra_number ). 10. The return statement is used to jump out of a function when a function is returned. We can also return a value from the function. For example: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;"> # Filename: func_return.py def maximum (x, y ): if x> y: return x elif x = y: return 'The numbers are equal' else: return y print (maximum (2, 3) </span> output: c: \ Users \ Administrator> python D: \ python \ func_return.py3 Working principle: the maximum value in the return parameter of the maximum function, here is the number provided to the function. It uses a simple if... else statement to find a large value and then return that value. Note that a return statement without a return value is equivalent to return None. None is a special type in Python that indicates nothing. For example, if the value of a variable is None, it indicates that it has no value. Unless you provide your own return statement, each function contains a return None statement at the end. By running print someFunction (), you can understand this. The someFunction does not use the return statement, as in [python] <span style = "font-family: Microsoft YaHei; font-size: 18px; "> def someFunction (): pass print (someFunction () </span> the output is None. Tip: python already contains a built-in function called max. Its function is to find the maximum value. You can use this function whenever possible. 11. DocStrings: Python has a wonderful feature called docstrings, which is usually referred to as DocStrings. DocStrings is an important tool because it helps your program documentation to be easier to understand. You can even restore the document string from the function when the program is running! For example: [python] <span style = "font-family: Microsoft YaHei; font-size: 18px;" ># Filename: func_doc.py def printMax (x, y ): www.2cto.com ''' Prints the maximum of two numbers. the two values must be integers. '''x = int (x) # convert to integers, if possible y = int (y) if x> y: print (x, 'is maximum') else: print (y, 'is maximum') printMax (3, 5) print (printMax. _ doc _) </span>

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.