A Byte of Python notes (5)

Source: Internet
Author: User
Tags uppercase letter

7th Chapter function

A function is an important segment of a program. They allow you to give a name to a statement, and then you can run the block of statements any number of times, anywhere in the program, using that name. This is called a call function.

Defining functions

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. Parentheses can include some variable names, which end with a colon. Next is a piece of statement, which is the function body.

# -*-coding:utf-8–*-
#def  SayHello ():    print'Hello world!!! ' SayHello ()

The above defines a function named SayHello, which does not use any parameters, and does not declare any variables in parentheses. Parameters for the function, just give the input to the function, so that the user can pass different values to the function, and then get the corresponding results.

function formal Parameters

The parameters that the function obtains are the values that the user provides to the function. These parameters are like variables, except that these values are defined when the user invokes the function, rather than in the function itself.

Parameters are specified within the parentheses of the function definition, separated by commas. When a user invokes a function, the value is provided in the same way.

Note: The parameter name in the function is a formal parameter, and the value provided to the function call by the user is called an argument.

# -*-coding:utf-8–*- #
def Printmax (A, B):     if a > b:        print'isMaximum'    else  :        print' isMaximum'printmax (3,4= 5  = 7printmax (x, y)

The above defines a function named Printmax, which has two parameters a, B.

In the first Printmax, we directly pass the number, i.e. the argument, to the function;

In the second Printmax, we use the variable to call the function; Printmax (x, y) assigns the value of argument x to parameter A, and the value of argument y to parameter B.

In two calls, the Printmax function works exactly the same.

Local variables

When a user declares a variable within a function definition, they have no relation to other variables of the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable. All variables are scoped to their defined blocks, starting with the point where their names are defined.

# -*-coding:utf-8 _*_ # Filename:func_local.py def func (x):     Print ' x is ' , x     = 2    print'Changed local xto'=print  Func (x)print'x is still', X

In the function, the first time we use the value of X, Python uses the value of the formal parameter declared by the function.
Next, we assign the value 2 to X. X is the local variable of the function. So, when we change the value of x within a function, the x defined in the main block is unaffected.

Using the global statement

If you want to assign a value to a variable that is defined outside the function, then you have to tell Python that the variable name is not local, but global. We use the global statement to complete this function. Without the global statement, it is impossible to assign a value to a variable that is defined outside the function.

Using the global statement makes it clear that the variable is defined outside the block.

#-*-coding:utf-8-*-#Filename:func_global.pydeffunc ():GlobalxPrint 'x is', x x= 2Print 'Changed local x to', XX= 50func ()Print 'Value of x is'X

The global statement is used to declare that X is global-so when we assign a value to x within a function, the change is 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, Z.

Default parameter values

For some functions, the user may want some of its parameters to be optional, and if the user does not provide a value for these parameters, the default values are used. This function is done using the default parameter values. You can assign default parameter values to parameters by adding the assignment operator (=) and the default value after the parameter name of the function definition.
Note that the default parameter value should be a parameter. More precisely, the default parameter values should be immutable.

# -*-coding:utf-8-*- #  def say (message, times = 1):    Print message * Timessay (' Hello ' ) Say ('World', 5)

The function named say is used to print a string any number of times required. If you do not provide a value, the string will be printed only once, by default. We do this by assigning a default parameter value to the parameter times.

When using say for the first time, we provide only one string, and the function prints the string only once. In the second use of say, we provided a string and a parameter of 5, indicating that we wanted to say this string message 5 times.

Important
Only those parameters at the end of the formal parameter list can have default parameter values, that is, you cannot declare a formal parameter with a default value when declaring a function parameter, and then declare a formal parameter that has no default value. This is because the value assigned to the parameter is assigned according to the position.
For example, Def func (A, b=5) is valid, but def func (a=5, b) is not valid.

Key parameters

If a function has many parameters, and the user only wants to specify a subset of them, you can assign a value to the parameters by naming them-this is called the key parameter-we use the name (the keyword) instead of the location to assign the argument to the function.

There are two advantages:

One, since we don't have to worry about the order of the parameters, it's easier to use the function.

Second, assuming that the other parameters have default values, we can only assign values to the parameters we want.

# -*-coding:utf-8-*- #  def func (A, b=5, c=10):    print'ais' and bis"andCis", Cfunc (3, 7) func ( c=24) func (c=50, a=100)

A function named Func has a parameter with no default value, and two parameters with a default value.
When the function func (3, 7) is used for the first time, A and B are assigned according to the actual argument position, and the parameter C uses the default value of 10.
The second time the function func (c=24) is used, a value of 25 is obtained based on the positional variable a of the argument. According to the name, i.e. the key parameter, the parameter C gets the value 24. Variable B is based on the default value, which is 5.
The third time you use Func (c=50, a=100), use key parameters to fully specify the parameter values. Note that although a is defined before C in the function definition, we can still specify the value of the parameter C before a.

Return statement

The return statement is used to return from a function, that is, to jump out of a function. We can also return a value from the function.

# -*-coding:utf-8-*- # Filename:func_return.py def maximum (x, y):     if x > y:        return  x    Else:          return  yprint maximum (8, 5)

Note that a return statement with no return value is equivalent to return none. None is a special type of Python that represents nothing. For example, if a variable has a value of none, you can indicate 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 (), return none, the function someFunction does not use the return statement, as follows:

def someFunction ():     Pass

The pass statement represents an empty block of statements in Python.

Docstrings

Python has a fantastic feature, called a document string, which is often referred to as docstrings. Docstrings is an important tool that makes the program documentation easier to understand and recommend to use. You can even recover a document string from a function while the program is running!

#-*-coding:utf-8-*-#Filename:func_doc.pydefPrintmax (x, y):" "Prints The maximum of the numbers. The values must be integers." "x= Int (x)#Convert to integers, if possibley =Int (y)ifX >y:PrintX'is maximum'    Else:        PrintY'is maximum'Printmax (5, 7)PrintPrintmax.__doc__

The string of the first logical line of the function is the document string for the function. Note that Docstrings also applies to modules and classes.

The Convention of a document string is a multiline string. The first line starts with an uppercase letter, the period ends, the second line is a blank line, and the third line starts with a detailed description. It is strongly recommended that you follow a document string in a function.

docstings function: Grab the __doc__ property of the function and show it neatly to you.

Include Help (Printmax) in the program and press Q to exit help.

Automation tools can also extract documents from your program in the same way.

A Byte of Python notes (5)

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.