Functions in Python receive extra parameters

Source: Internet
Author: User

Code:

def Fun (x):     return x     Print Fun (10)

The function fun (x) accepts the argument is x, passing in the number "10", the return value of the print function is 10, if I pass multiple parameters, the program will go wrong, such as:

def Fun (x):     return x Print (Fun (10,20))
Traceback (most recent):   " aa.py "  in <module>    print(10,201 argument (2 given)

The result is: 2 parameters are given. To solve this problem, introduce *args to put the extra parameters into the tuple, such as:

def Fun (x, *args):    print  args    return  x     Print(Fun (10,20))

In this case, X only accepts the first parameter, and the others are stored in the args tuple, as a result:

(10,)

Tuple is not stored in the dictionary type of data, if I store the dictionary type data will be error? See:

def Fun (x, *args):    print  args    return  x      Print(Fun (10,20,y=2))
Traceback (most recent):   " aa.py "  in <module>    print(10,20,y=2'y'

At this point, give an error: Catch an unknown keyword parameter y, in order to solve this we need to introduce **kw to solve the incoming parameter is the dictionary type of data, see:

def Fun (x, *args, * *kw)    :print  kw    print  args     return x     Print (Fun (10,20,y=2))

Running results such as:

{'y': 10}

Look at the whole effect:

def Fun (x, *args, * *kw)    :print  kw    print  args      return  x    print(Fun (10,20,40,50.5,y=2,z=3,f=5.5))

Operation Result:

{'y'z'f': 5.5} (+, 50.5)10

The main note is: Fun (x, *args, **kw) when the function is called, the incoming dictionary parameter is not allowed to pass in x = * This type, there will be an error, such as:

Traceback (most recent):   " aa.py "  in <module>    print(10,20,40,50.5,z=3,x=2,y=5.5for'  x'
  " aa.py ", line 9    print(x=2,10,20,40,50.5,z=3,y=5.5)) Syntaxerror:non-keyword Arg after Keyword arg

Functions in Python receive extra parameters

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.