Python2.x_ function

Source: Internet
Author: User

The function name is actually a reference to a function object, which assigns the function name to a variable

1 Defining functions

1.1 Single return value

def myadd (x, y):

Return X+y

Print Myadd (3,4)

1.2 Multiple return values (return tuple tuple)

def mymaxmin (x, y):

return Max (x, y), min

Max, min = mymaxmin (3,4)

Print Max, min

m = mymaxmin (3,4)

Print m

1.3 Default function (required parameter is before, default parameter is after, default parameter must point to immutable object)

Import Math

def mypower (x, n=2):

Return X**n

Print Mypower (5)

Print Mypower (5,3)

Print Mypower (n=3, x=5)

1.4 variable parameters (incoming as a tuple, 0 or any parameter passed in)

def mySum (*num):

sum = 0

For n in Num:

sum = SUM + N

return sum

Print MySum

Print MySum (+/-)

1.5 keyword parameter (incoming as dict, pass in 0 or any parameter with parameter name)

def person (name, age, **kw):

print ' name: ', Name, ' Age: ', age, ' other: ', kw

Person (' Adam ', gender= ', ' M ', job= ' Engineer ')

1.6 parameter Combinations

Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4

def func (A, B, c=0, *args, **kw):

For any function, it can be invoked in the form of a func (*args, **kw), regardless of how its arguments are defined.

Python2.x_ function

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: 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.