Python Learning notes: Functions

Source: Internet
Author: User

Python functions

First look at the following code:

def welcome_info ():     " Show welcome message "    Print ("Hello world! " )    return 0

As in the code, a function is defined.

The result after the call is:

Welcome_info ()     # call function Hello world!        # Call Result

Here, we refer to the Python Official document definition of the Python function:

The keyword def introduces a function definition. It must is followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must is indented.

The keyword def introduces a function definition. It must be followed by a function name (that is, the function name) and a pair of formal parameter columns that are wrapped in parentheses (nullable). A statement statement that forms the body of a function starts at the next line and is forced to indent.

Here, add two points:

The first line after the colon is preferably a string that is wrapped in double quotation marks to enable the programmer and others to quickly know their function and meaning when they are searched and called later. Getting into a good writing habit is best to start from scratch.

The last line of the function body usually ends with a return statement.

It says how to define a function, so what's the use of the function, after reading the following code maybe you can understand something:

defresult ():Print("lay down a bird")defhunt1 ():"hit the bird 1"    Print("I shot an arrow.") result ()defHunt2 ():Print("I fired a shot.") result ()defHunt3 ():Print("I shot a gun.") result () Hunt1 () Hunt2 () Hunt3 ()

Operation Result:

I shot an arrow and I laid a bird, I shot a bird, I hit a puffing out, I hit a bird.

When you need to invoke the same function multiple times in a program, the function is reflected, that is, the function avoids repeating the code .

Then look at the following code:

Import Timedefresult (): Time_format="%y-%m-%d%x"time_current=time.strftime (Time_format)Print("lay down a bird%s"%time_current)defhunt1 ():"hit the bird 1"    Print("I shot an arrow.") result ()defHunt2 ():Print("I fired a shot.") result ()defHunt3 ():Print("I shot a gun.") result () Hunt1 () Hunt2 () */hunt3 ()

The result is:

I shot an arrow and laid a bird-11-29 17:14:06 I fired a shot down a bird-11-29 17:14:06 I hit a puffing out down a bird-11-29 17:14:06

Here we see that only the first function is modified, and the results of other functions that call the function are changed, which is the other two features of the function:

Consistency

Scalability

Return statement

Let's look at the following code:

def welcome_info ():     Print ("Hello world! " )    return  0    print("Hello python! " )    x = Welcome_info ()
Print (x)

Operation Result:

Hello world!
0

When the function executes, return forces the end and returns 0. 0 What does that mean? Look at the following code:

defhunt1 ():"hit the bird 1"    Print("I shot an arrow.")defHunt2 ():Print("I fired a shot.")    return0defHunt3 ():Print("I shot a gun.")    return2, 69,"Hello python!", ["BigBang","Bigcock"], {"size":"centimeters"}a=hunt1 () b=Hunt2 () C=Hunt3 ()Print(a)Print(b)Print(c)

Operation Result:

I shot an arrow and I fired a shot. None0 ('Hello python! ', ['bigbang'bigcock'], {'size  'centimeters'})

As you see from this section of code,

When there is no return statement, there is no returned value and the result is none;

Returns an object when the return value is 0 o'clock;

When the return value is a number, string, list, dictionary, a tuple that contains all preceding objects is returned.

The return value can be any length of any type.

formal Parameters & actual parameters & Default parameters & parameter Groups

Look at the following code:

def name (A, b    ): Print (a)     Print (b) name ("bigbang""bigcock")

Operation Result:

Bigbangbigcock

In the above code, the keyword def after name is the function name of this function, and the parentheses are the formal parameters a and B.

Why is a and b called formal parameters?

Because before assigning them a value, they are just A and B, with no real meaning, just an identity that is waiting to be assigned.

When the function is called, the parentheses give two actual arguments, BigBang and Bigcock, and their positions correspond to the formal parameters a and b one by one in parentheses after the function name.

At this point the actual parameters are also called positional parameters .

Now you have the following code:

def name (A, b    ): Print (a)     Print  "bigbang" "bigcock")

Operation Result:

Bigcockbigbang

When the function name is called, the assignment of the formal parameter is specified in parentheses, at which point the actual parameter is called the key parameter. They are independent of the position of the formal parameter, but the quantity must correspond.

Look at the following code:

def " BigBang " ):    print(a)    print(b) name ("Bigcock ")

Operation Result:

Bigcockbigbang

In this example, when we call a function, we do not pass two values to name, but the output is still two values.

This is because we have assigned a value to form parameter B in advance when defining the function, where B = "BigBang" is called the default parameter .

The call simply passes a real argument to a.

Look at the following code:

def " BigBang " ):    print(a)    print(b) name ("bigcock " " Lovefuck ")

The results are as follows:

Bigcocklovefuck

In the example above, when the function name is called, two actual arguments are passed. The assignment of B in the result of the run is changed from "BigBang" defined in the formal parameter to "Lovefuck".

Thus, one of the characteristics of the default parameter is:

When a function is called, the default parameter must not be passed. By using the default parameters, you can set some default values in the program to improve the efficiency of the program operation.

When there are multiple actual parameters, it can be defined as follows:

def Numbers (*args):    print(args) numbers (23, 62, 79, 1, 28, 99)

Results:

(23, 62, 79, 1, 28, 99)

Args is the abbreviation for arguments, * is a reference method, the computer language means all, for example, we want to search all the pictures on the computer, you can enter "*.jpg" in the search field. At this point the computer automatically searches all JPG-formatted image files in the computer.

Here, when we call the function and pass multiple arguments to args, args encapsulates all the actual arguments as a tuple.

The above example can also be written like this:

def numbers (A, b, *args):    print(a)    print(b)     Print (args) numbers (23, 62, 79, 1, 28, 99)

Results:

2362(79, 1, 28, 99)

When a function is defined, two parameters are passed and a parameter group is called, and the actual parameters are assigned to the formal parameters according to their location, and the actual parameters that are not assigned to the formal parameters are all assigned to the parameter group.

To continue, look at the following example:

def user_info (* *Kwargs)    :print"bigbang""  m""""Girl")

Operation Result:

{'name'bigbang'sex'  m'age'  Hobby'girl'}

In the example, Kwargs is the abbreviation for key word arguments, meaning the keyword parameter group.

It can also be found that when we call a function, Kwargs encapsulates the key parameters that are passed in the call as a dictionary.

When passing more than one type parameter, be aware of the following points:

The default parameter must be written in front of the parameter group;

When a function is called, the positional parameter must precede the key parameter.

After the previous study, we can write a common function, if you are a gamer, you can use this function to understand the functions of the various parameters of the definition:

defLogin (name, pw, difficulty ="Normal", *args, * *Kwargs):Print(name)Print(PW)Print(difficulty)Print(args)Print(Kwargs) login ("BigBang","123456","Beginner","Start Game","quit","Previous Page", map ="lost Temple")

Operation Result:

BigBang123456Beginner ('start game' 'quit'  'previous page') {'map'  lost Temple'}

In the example, the first two actual arguments that are passed when the parameter is called correspond to the first two bits of the formal parameter, the third positional parameter changes the assignment of the default parameter in the definition to "beginner", and if the positional parameter is not passed, the difficulty here becomes "Start Game", This is obviously not the result we want, then all three positional parameters are passed to args, forming a tuple, and the final key parameter is passed to Kwargs.

Python Learning notes: Functions

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.