Python: Functions

Source: Internet
Author: User

Import Math def Move (x, y, step, angle=0):    = x + step * math.cos (angle)    = Y-step * Math.sin (A Ngle)    return NX, NY

import mathThe statement represents the import math package and allows subsequent code to reference math the function in the package sin cos .

Then we can get the return value at the same time:

>>> x, y = Move (MATH.PI/6)print(x, y)151.96152422706632 70.0

But this is just an illusion, and the Python function returns a single value:

>>> r = Move (MATH.PI/6)print(r) (151.96152422706632, 70.0)

The original return value is a tuple! However, in syntax, the return of a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by the location of the corresponding value, so the Python function returns a multi-value is actually returned a tuple, but it is more convenient to write.

函数的参数
规则:
  1. 是必选参数在前,默认参数在后,否则Python的解释器会报错(思考一下为什么默认参数不能放在必选参数前面);
  2. 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。
    defEnroll (name, Gender, age=6, city='Beijing'):    Print('Name:', name)Print('Gender:', gender)Print('Age :', age)Print('City :', city)

    Only students who do not match the default parameters need to provide additional information:

    Enroll ('Bob'M', 7) Enroll ('Adam  'M', city='Tianjin')

    Visible, the default parameters reduce the difficulty of function calls, and once more complex calls are required, you can pass more parameters to implement. The function only needs to define one, whether it is a simple call or a complex call.

    When there are multiple default parameters, when called, the default parameters can be provided in order, such as calls enroll(‘Bob‘, ‘M‘, 7) , meaning that, in addition name to gender these two parameters, the last 1 parameters are applied on the parameter age , and the city parameter is still using the default value because it is not provided.

    You can also provide some default parameters in order, not sequentially. When you do not provide partial default parameters in order, you need to write the parameter names. For example, the call enroll(‘Adam‘, ‘M‘, city=‘Tianjin‘) , meaning that the city parameter is passed in the value, the other default parameters continue to use the default value.

  3. The default parameters are useful, but improper use will also fall out of the pit. The default parameter has a maximum pit, which is shown below:

    First define a function, pass in a list, add one and END return:

    def add_end (l=[]):    l.append ('end')    return L

    When you call normally, the result looks good.

    >>> Add_end ([1, 2, 3])[1, 2, 3,'END']>>> Add_end (['x','y','Z'])['x','y','Z','END']

    When you use the default parameter call, the result is also right at the beginning:

    >>> add_end () ['end']

    However, when called again add_end() , the result is incorrect:

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

    The reasons are explained as follows:

    When the Python function is defined, the value of the default parameter is L calculated, that is [] , because the default parameter L is also a variable, which points to the object [] , each time the function is called, if the change L of content, the next call, the contents of the default parameters will change, is no longer the function definition [] .

    So, one thing to keep in mind when defining default parameters: The default parameter must point to the immutable object!

    To modify the example above, we can use None this invariant object to implement:

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

    Why design str , None such an immutable object? Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.

Python: Functions

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.