Python basic "day04": function introduction, parameter invocation

Source: Internet
Author: User

The content of this section

function Introduction

function parameters and calls

Non-fixed parameters of a function

Introduction to Functions, Introduction

In our previous learning programming process, we encountered the most two programming ways or programming methods: process-oriented and object-oriented. In fact, no matter what kind of, in fact, is the methodology of programming. But now there is an older way of programming: Functional programming, which re-enters our horizons with features such as its unsaved state, non-modification of variables, and so on.

Object-Oriented---> class---->class
Process-oriented---> Process--->def
Functional programming---function--->def

Second, function definition

We went to junior high school that will also learn the function, that is: y=2x, plainly, this is a total of two variables x and y,x are independent variables, y is the dependent variable (because x changes), Y is the function of X. The value range of the argument is called the definition field of the function.

Speaking so much, let's talk about the function definition in programming!!!

1. Function definition:
2. Process definition:
3. Comparison between the two:
Summary: It is not difficult to see that functions and procedures actually do not have too many bounds in Python, when there is return, the output return value, when there is no return, then return none

Third, the reason of using function

At this point, we have understood the function, but why do we use the function ah, I think we used to the kind of writing is very good ah! In fact, I have summed up the two benefits of using the function:

Code re-use
Scalability
Maintain consistency

1. Code Reuse

We usually write code, the most annoying is to write duplicate code, this is undoubtedly to increase our workload, so code reusability is very necessary. Let's give a simple example of the difference between using a function and not using a function.

① before optimization
So suppose there are n functions, do we have to copy n times? So, we were born with the following method

② after optimization

2, extensible, consistent code

Note: If you encounter code logic changes, using the method of copying n times before, then when the copy finished Ah, and the middle of the omission how to do, if the function, we only need to change the logic of this function, do not change anywhere else.

function parameters and call one, return value


Previously mentioned in the day3-function introduction of the return keyword, but the only mention, and no detailed introduction of the return keyword usage, below we will elaborate.

1. Return function

Return actually has two functions:

You need to use a variable to accept the result returned after the program ends
It is used as a terminator to terminate the program run
Note: As can be seen from the above code, the code after return 0 does not execute, only the code returned before the return, the variable x accepts the test () function after the end of the result

2. Return multiple values

Above we tried to return a constant value, or an object value, let's try it, do not return a value, or return more than one worthwhile case.
As can be seen from the above example:

No definition, number of return values = 0, return: None
Only 1 return values are defined, return value =1, return: The defined value, or the defined object
More than 2 defined, return value > 1, return: 1 tuples (tuple)
Question: Here we inadvertently ask, why should have return value?

Because we want to get the execution result of this function, the result of this execution will be used in the process of running the program later.

Second, the parameter function call


Until then, the functions we demonstrated were all without parameters, so let's say a function with parameters. Before we speak, let us first say what is a formal parameter and what is an argument!

Formal parameters: refers to the formal parameter, is virtual, does not occupy the memory space, the parameter element only allocates the memory unit when called.
Argument: refers to the actual parameter, is a variable, takes up memory space, the data is passed one way, the argument is passed to the formal parameter, the parameter cannot be passed to the argument
The code is as follows:

1. Position parameters

As can be seen from the above example, the actual parameters and formal parameters are one by one corresponding, if the swap position, x and y are called, the position is also interchangeable, the code is as follows:
Then some students say, I have one or fewer parameters, it is all right! Can I have a look at it?

① One more parameter
② less one parameter

2. Keyword parameters

To this side some small partners inadvertently to say, like this positional parameters, a little dead, I do not want to do so, in case I pass the wrong to do, right! OK, no problem, let's talk about keyword transfer.

The keyword argument does not need to be one by one, you only need to specify which parameter you want to call which argument, the code is as follows:

However, this is another small partner to ask, then I can be positional parameters and keyword parameters together with the Na? Next, let's explore.

① position parameter in front, keyword argument after
I rub this is possible, then I try this situation, I put the following key words do not pass to Y, I passed to X, the code is as follows:

The error means that there are too many values to pass to the parameter x. The reason for this error is: Argument 1 has been passed to the formal parameter x, after the x=2 and passed again, so error.

② keyword in front, position parameter in rear
I'll go, it doesn't look like this. Then I put the positional parameters in front, the middle of the keyword parameters in the head! The code is as follows:

Still the same mistake, I go, then I can only put the keyword parameter last try!

So I'm the last two to use the keyword parameter?

Summarize:

When both keywords and positional parameters are available, the order of positional parameters is
The keyword parameter is not written in front of the position parameter

An overview of the non-fixed parameters of a function

In the previous blog I have written, positional parameters and keyword parameters, let's talk about the default parameters and parameter groups

Second, default parameters

The default parameter refers to the setting of a default value for the parameter before we pass the argument. When we call a function, the default parameter is a non-mandatory pass.

123456789101112131415161718192021 deftest(x,y=2):    print(x)    print(y) print("-----data1----")test(1#没有给默认参数传值print("-----data2----")test(1,3#给默认参数传位置参数print("-----data3----")test(1,y=3)  #给默认参数传关键字参数#输出-----data1----12-----data2----13-----data3----13

Default parameter usage:

    • Install default software (Def test (x,soft=true))
    • Pass the default value (define MySQL's default port number: Def count (host,port=3306))
Three, parameter group

Before we pass the parameters, we pass a fixed parameter, we can't do more and less, but what if we need non-fixed parameters? All right, so the following two kinds of communication methods are derived:

    1. Non-fixed positional parameter parameters (*args)
    2. Non-fixed keyword pass-through (**kwargs)

Let's say these two ways to pass the argument:

1, non-fixed position parameter transfer

① function: receives n position parameter, transforms the form of the Narimoto group.

② definition, the code is as follows:

1234567 deftest(*args): #形参必须以*开头,args参数名随便定义,但是最好按规范来,定义成args    print(args)test(1,2,3,4,5#输入多个位置参数#输出(12345)  #多个参数转换成元组

This way can not help but have a question, you this is passed n positional parameters, then I want to pass in an entire list, I want to fully get the value of this list.

③ Incoming List

1234567891011121314151617 deftest(*args):    print(args)print("-------data1-----")test() #如果什么都不传入的话,则输出空元组print("-------data2-----")test(*[1,2,3,4,5])  #如果在传入的列表的前面加*,输出的args = tuple([1,2,3,4,5])print("-------data3-----")test([1,2,3,4,5])  #如果再传入的列表前不加*,则列表被当做单个位置参数,所以输出的结果是元组中的一个元素#输出-------data1-----()-------data2-----(12345)-------data3-----([12345],)

④ positional and non-fixed positional parameters

123456789 deftest(x,*args):    print(x)  #位置参数    print(args)  #非固定参数test(1,2,3,4,5,6)#输出1(23456

As seen from the above, the 1th parameter, which is treated as the positional parameter, is treated as a non-fixed position parameter.

⑤ keywords and non-fixed positional parameters

1234567891011 deftest(x,*args):    print(x)    print(args)test(x=1,2,3,4,5,6)#输出  File "D:/PycharmProjects/pyhomework/day3/非固定参数/非关键字参数.py", line 21    test(x=1,2,3,4,5,6)            ^SyntaxError: positional argument follows keyword argument #位置参数在关键字参数后面

Obviously error, because x=1 is the keyword parameter, *args is the positional parameter, and the keyword parameter can no longer precede the position parameter, so error.

2. Non-fixed key-word transfer parameter

function: convert n keyword parameters into a dictionary form

② definition, the code is as follows:

③ Incoming Dictionary
However, some small partners said, I do not believe, do not add * *, will be error, then why the non-fixed position parameters *, why do not error? Let's talk about the facts below, the code is as follows:
Because the passed-in dictionary is treated as a positional parameter, it is reported to be of the wrong type, so the small partners must remember: to pass the dictionary, plus * *

④ Mate Position parameter use
⑤ positional parameters, keywords, and non-fixed keyword parameters

Hint: The parameter group must go to the last place
Note: That is, if you encounter a keyword and non-fixed keyword parameters, the position of the front and back is not affected by the parameters, but we generally still in order.

⑥ positional parameters, keyword parameters, non-fixed positional parameters, and non-fixed keyword parameters

Then the question comes, the above age pass is the positional parameter, then I can pass the keyword parameter na? Now let's take a look at the code as follows:
It doesn't seem to be possible, why? Because age=19 is the keyword parameter, and the back of the *args is a non-fixed position parameter, white, regardless of the *args incoming a few words, it is the essence of the positional parameters, the above we mentioned that the keyword parameter is no longer in front of the positional parameters, so the error.

It seems that the above situation is not possible, that can not be invariant keyword parameters in the non-fixed position parameters in front of it? Come on, let's try it with a question. The code is as follows:

I wipe, also can not, after my careful study found that the non-fixed keyword parameters, the essence is also the keyword parameters, is not placed in the non-fixed position parameters of the front.

Iv. Summary
    1. Parameters are divided into positional parameters, keyword parameters, default parameters, non-fixed positional parameters, and non-fixed keyword parameters
    2. Position parameters before the parameter, position is not interchangeable, one or fewer parameters are not possible.
    3. The keyword parameter cannot be placed in front of the position parameter.
    4. The position of the function parameter is once, the position argument, the default parameter, the non-fixed positional parameter, the non-fixed keyword parameter (def test (Name,age=18,*args,**kwargs))
    5. keyword, you can not consider the location of the problem before and after

Python basic "day04": function introduction, parameter invocation

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.