First question about Liao Xuefeng's python Tutorial: Liao Xuefeng's python tutorial

Source: Internet
Author: User

First question about Liao Xuefeng's python Tutorial: Liao Xuefeng's python tutorial

Function parameters are described in the section:

Def add_end (L = []);

L. append ('end ')

Return L

When add_end is called normally (that is, when parameter data transmission is available ):

  

>>> Add_end ([1, 2, 3]) [1, 2, 3, 'end'] >>> add_end (['x', 'y ', 'Z']) ['x', 'y', 'z', 'end']

When default parameters are used:
>>> add_end()['END']

>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']

Liao Xuefeng explained the following:

When defining a Python function, the default parameterLIs calculated, that is[]Because the default parametersLIt is also a variable that points to the object[]. If this function is called every timeLThe content of the default parameter changes next time, instead of when the function is defined.[].

My understanding is as follows:

In the first line, input the parameter [, 3]. The following code is for [, 3]. It has nothing to do with L = []. The third line is the same as the first line, L = [] is not involved in these two times, so the value of L remains unchanged. The second line does not include parameters, so the following code is for L, from [] to ['end'], and the fourth line is for L, however, the value of L has been changed to ['end'] and is run again, so it becomes ['end', 'end'].

The improvement method is as follows:

def add_end(L=None):    if L is None:        L = []    L.append('END')    return L

>>> add_end()['END']>>> add_end()['END']

But I still don't understand the sentence if L is None: L = []. I hope I can understand it later.
 
 

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.