Python learning notes-functions and python learning notes

Source: Internet
Author: User

Python learning notes-functions and python learning notes

1. Define the function:

In Python, define a function to usedefStatement, write the function name, parameters in parentheses, and colons in sequence:Then, write the function body in the indent block. The return value of the function isreturnStatement. If a function does not do anything, you need to use the pass Statement (C, Java can directly do not write code, python must write the pass placeholder, otherwise an error is reported ).

def my_abs(x):    if x >= 0:        return x    else:        return -x

 2. parameter check:

Isinstance (object, classinfo). The first parameter is the object, and the second parameter is a list of type names or type names. The return value is boolean. Returns True if the object type is the same as that of parameter 2. If the two parameters are a single tuples, True is returned if the object type is the same as one of the type names in the tuples.

def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError('bad operand type')    if x >= 0:        return x    else:        return -x

3. Multiple values are returned:

The python parameter can return multiple values, which are essentially a single tuples. Multiple variables can receive one tuples at a time and assign values by position.

4. parameters:

  4.1 default parameters:

You can set a default value for a function parameter in python. When no corresponding parameter is input, it is processed by the default value. In the following example, 25 is printed.

def power(x, n=2):    s = 1    while n > 0:        n = n - 1        s = s * x    return sprint power(5)print power(5, 2)

When multiple default parameters exist, they can be passed in sequence or in the form of "parameter name = parameter value.

def enroll(name, gender, age=6, city='Beijing'):    print 'name:', name    print 'gender:', gender    print 'age:', age    print 'city:', city
enroll('Adam', 'M', city = 'Chengdu')
enroll('Tom', 'M', 7)

The default parameter value is generally an immutable object. Otherwise, the default parameter value may change with the call. For example:

def add_end(L=[]):    L.append('END')    return L
print add_end(),
print add_end()

The output is['END'] ['END', 'END']。

  4.2 variable parameters:

  Variable parameters mean that the number of input parameters is variable. In fact, they can also be implemented through lists or tuples. Variable parameters are as follows:

def calc(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum
print calc(1, 2, 3)
print calc()

If the parameters to be passed in are stored in the list, you can use calc (* listname ).

 4.3 keyword parameters:

Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function. ** Is added before the keyword parameter. The example is as follows:

def person(name, age, **kw):    print 'name:', name, 'age:', age, 'other:', kw

print person('Bob', 35, city='Beijing')
kw = {'city': 'Beijing', 'job': 'Engineer'}print person('Jack', 24, **kw)

4.4 parameter combination:

The four parameters can be used together, or only some of them are used. However, note that the order of parameter definitions must be: Required parameter, default parameter, variable parameter, and keyword parameter.

def func(a, b, c=0, *args, **kw):    print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw
Args = (1, 2, 3, 4) kw = {'X': 99} print func (* args, ** kw) # For any function, you can usefunc(*args, **kw)Call it in the form of # print the result: a = 1 B = 2 c = 3 args = (4,) kw = {'X': 99}

 

 

  

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.