Python Learning (6)

Source: Internet
Author: User
ArticleDirectory
    • 1. define functions:
    • 2. function parameters:
    • 3. Local variables:
    • 4. global variables:
    • 5. external variables:
    • 6. default parameter values
    • 7. Keyword (keyword) parameters:
    • 8. Variable (varargs) parameters:
    • 9. Key-only parameter:
    • 10. Return Statement
    • 11. Document string (docstrings ):
Vi. functions:

Functions are reused.Program. 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 functions:

For example:

# Filename: function1.py def sayhello (): Print ('Hello world! ') # Block belonging to the function # End of function sayhello () # Call the functionsayhello () # Call the function again

Output:

C: \ Users \ Administrator> Python D: \ Python \ function1.py

Hello world!

Hello world!

Working principle:

We use the syntax described above to defineSayhello. 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:

# Filename: func_param.py def printmax (A, B): If A> B: Print (A, 'is maximum') Elif A = B: Print (, 'is equal to', B) else: Print (B, 'is maximum') printmax (3, 4) # directly give literal values x = 5y = 7 printmax (X, y) # Give variables as arguments

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_param.py

4 is maximum

7 is maximum

Working principle:

Here, we define a function called printmax. This function 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:

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

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_local.py

X is 50

Changed local X to 2

X is still 50

Working principle:

When we use the value of X for the first time in a function, 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 this method as follows:

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

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_global.py

X 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 have known how to use local variables and global variables, and an external variable is a variable between the above two variables. When we declare external variables in the function, they are visible in the function.

Everything is executable in Python.CodeSo 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 external variables:

 
# 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 ()

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_nonlocal.py

X is 2

Changed local X to 5

Working principle:

When we are in the func_inner () function, the variable X defined in the first line of the function func_outer () is neither an internal variable (it is not in the func_inner block) it is not a global variable (it is not 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 its 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:

 
# Filename: func_default.py def say (message, Times = 1): Print (Message * times) Say ('hello') Say ('World', 5)

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_default.py

Hello

Worldworldworldworld

Working principle:

The function named "say" is used to print any number of times required by a string. 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, when you cannot declare a function parameter, you must first declare a parameter with the default value 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,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, you can assign values to these parameters by name. This is called a keyword parameter. We use the name (keyword) instead of specifying the real parameter for the function (the method we used previously.

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:

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

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_key.py

A 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 two parameters without default values, and two parameters with default values.

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. Variable (varargs) parameters:

Sometimes you may want to define a function that can accept any number of parameters. You can use an asterisk to complete the function.

For example:

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

Output:

C: \ Users \ Administrator> Python D: \ Python \ Total. py

166

Working principle:

When we declare a parameter as a star, such as * Param, all the real parameters from this position to the end will be collected in the 'param' Meta Group. Similarly, when we declare a form 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. Key-only parameter:

If we want some key parameters to be obtained only through the real parameter instead of the position, we can declare them behind the asterisk parameter.

For example:

# 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'

Output:

C: \ Users \ Administrator> Python D: \ Python \ keyword_only.py

66

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:

After an asterisk (*) is declared, it is a keyword-qualified 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, suchTotal (initial = 5, *, extra_number).

10. Return Statement

Return statements are used to jump out of a function when a function is returned. We can also return a value from the function.

For example:

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

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_return.py

3

Working principle:

The maximum value in the return parameter of the maximum function. Here it 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 shown below:

 
Def somefunction (): passprint (somefunction ())

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. Document string (docstrings ):

Python has a wonderful feature called a document string, 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:

# Filename: func_doc.py def printmax (x, y): ''' 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 __)

Output:

C: \ Users \ Administrator> Python D: \ Python \ func_doc.py

5 is maximum

Prints the maximum of two numbers. The two values must be integers.

Working principle:

The string in the first logical line of the function is the document string of the function. At the same time, docstrings also applies to modules and classes. We will learn about them in the following chapters.

A document string is a multi-line string whose first line starts with an uppercase letter and ends with a full stop. The second line is empty, and the detailed description starts from the third line. We strongly recommend that you follow this Convention when using document strings in functions.

You can use _ Doc _ (note Double underline) to call the document string attribute of the printmax function (belongs to the function name ). Python regards everything as an object, including this function.

If you have used help () in Python, you have seen the use of docstings! All it does is capture the _ Doc _ attribute of the function and display it to you neatly. You can try the above function-just include help (printmax) in your program ). Remember to press Q to exit help.

Automated tools can also extract documents from your programs in the same way. Therefore, we strongly recommend that you write document strings for any formal functions you write. Use the pydoc command that comes with your python release, similar to help () to use docstrings.

Related Article

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.