Python Basic if and Function__python

Source: Internet
Author: User
Tags function definition

from:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 00137473843313062a8b0e7c19b40aa8f31bdc4db5f6498000

If statement syntax:

If < condition judgment 1>:
    < execution 1>
elif < conditional judgment 2>:
    < execution 2> Elif
< conditional judgment 3>:
    < execution 3>
Else:
    < executive 4>
function Definition Example:

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

Def NOP (): Pass
    
function can return multiple values

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

But it's just an illusion, and the Python function returns a single value:

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

The original return value is a tuple. However, in syntax, returning a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by position to the corresponding value, so Python's function to return a multi-valued is actually to return a tuple, but it is more convenient to write. Functions can have default parameters

There are pits:

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

When you invoke Add_end () again, the result is incorrect:

>>> add_end ()
["End", "End"]
>>> add_end () ["End", "End", "End"
]

Explanations for the reasons are as follows:

When the Python function is defined, the value of the default parameter L is computed. That is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if the contents of L are changed, the contents of the default parameter will be changed at the next call, no longer the [] of the function definition.

So, to define the default parameters, keep in mind that the default argument must point to the invariant object.

To modify the example above, we can implement the invariant object with none:

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

Why do you want to design a constant object such as Str and none? Because once the invariant object is created, the data inside the object cannot be modified, thus reducing the error caused by the modification of the data. In addition, because the object is invariant, the multitasking environment reads the object without the need for locking, while reading the problem is not. When we write a program, if we can design a invariant object, then try to design unchanged objects.

variable parameter normal list or tuple parameter transfer (not variable parameter mode):

def calc (numbers):
    sum = 0 for
    n in numbers:
        sum = SUM + N * n * return
    sum

But when you call, you need to assemble a list or tuple first:

>>> Calc ([1, 2, 3])
>>> Calc ((1, 3, 5, 7))
84

Change the parameter of the function to a variable parameter:

Def calc (*numbers):
    sum = 0 for
    n in numbers:
        sum = SUM + N * n * return
    sum

When you define a variable parameter and define a list or tuple parameter, you simply add a * number to the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any of the arguments, including 0 parameters:

>>> Calc (1, 2)
5
>>> calc ()
0

If you already have a list or tuple, what to do if you want to invoke a variable parameter. You can do this:

>>> nums = [1, 2, 3]
>>> Calc (nums[0], nums[1], nums[2])
14

This kind of writing is certainly feasible, the problem is too cumbersome, so python allows you to add a * number in front of the list or tuple, the list or tuple elements into variable parameters to pass in:

>>> nums = [1, 2, 3]
>>> calc (*nums)
14

This kind of writing is quite useful and very common. keyword Parameters

Variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with a parameter name, which is automatically assembled into a dict within the function. Take a look at the example:

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

The function person accepts the keyword parameter kw in addition to the required parameter name and age. When you call the function, you can pass in only the required parameters:

>>> person (' Michael, "
Name:michael age:30 other: {}

You can also pass in any number of keyword parameters:

>>> person (' Bob ', "city= ' Beijing ')
name:bob age:35 Other: {" City ": ' Beijing '}
>>> person ( ' Adam ', gender= ' m ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}
parameter Combinations

To define a function in Python, you can use required parameters, default parameters, variable parameters, and keyword parameters, all 4 of which can be used together, or only some of them, but note that the order in which the parameters are defined must be: required, default, variable, and key parameters.

For example, define a function that contains the 4 parameters mentioned above:

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

When the function is called, the Python interpreter automatically passes the corresponding arguments in the parameter position and the argument name.

>>> func (1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> func (1, 2, c=3)
a = 1 b = 2 c = 3 arg  s = () kw = {}
>>> func (1, 2, 3, ' A ', ' B ')
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {}
>>> Func (1, 2, 3, ' A ', ' B ', x=99)
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {' X ': 99}

The most amazing thing is that you can call the function through a tuple and dict:

>>> args = (1, 2, 3, 4)
>>> kw = {' X ':}
>>> func (*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {' X ': 99}

Therefore, for any function, it can be invoked in the form of a similar func (*args, **kw), regardless of how its parameters are defined. Summary

Python's functions have a very flexible parameter shape that enables both simple calls and very complex parameters.

The default parameter must be an immutable object, and if it is a mutable object, there will be a logical error in the operation.

Note The syntax for defining variable parameters and keyword parameters:

Related Article

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.