Passing function parameters in Python

Source: Internet
Author: User

1. The most common form. parameters are separated by commas. The number of parameters must be consistent.
>>> Def test (x, y): <br/>... print X, Y <br/>... <br/> test (1, 2) <br/> 1 2 <br/>

2. provide default values

>>> Def test (X, Y = 2): <br/>... print X, Y <br/>... <br/> test (1) <br/> 1 2 <br/>

 

3. If the number of parameters is not fixed, add the parameter. In a function, parameters are stored as tuple.

>>> Def test (* X): <br/>... print Len (x) <br/>... print x <br/>... <br/> test () <br/> 0 <br/> () <br/> test (1) <br/> 1 <br/> (1,) <br/> test (2, 4) <br/> 2 <br/> (2, 4) <br/> </P> <p>

 

4. The number of parameters is not fixed. ** Add the form parameter name. Within a function, parameters are stored in a dictionary.

>>> Def test (** X): <br/>... print Len (x) <br/>... print x <br/>... <br/> test () <br/> 0 <br/>{}< br/> test (x = 1, y = 3, z = 5) <br/> 3 <br/> {'y': 3, 'x': 1, 'z': 5} <br/>

 

5. A combination of the above four methods. By method 1 ~ 4. parse parameters one by one.

>>> Def test (X, Y = 1, * m, ** N): <br/>... print X, Y, m, n <br/>... <br/> test (1) <br/> 1 () {}< br/> test (1, 2) <br/> 1 2 () {}< br/>>>> test (1, 2, 4) <br/> 1 2 (4,) {}< br/>>>> test (1, 2, 4, 5, A = 'B') <br/> 1 2 (4, 5) {'A': 'B'} <br/>>>< br/>

 

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.