Python Learning Notes _ one hour a day 8.24

Source: Internet
Author: User

8.24

Function

To invoke a function, you need to know the name and parameters of the function, such as a function that asks for an absolute value abs , and only one argument. Documents can be viewed directly from the official Python website:

Http://docs.python.org/2/library/functions.html#abs

You can also help(abs) view the abs function's help information on the interactive command line.

comparison function cmp(x, y)It takes two parameters, if x<yReturn -1If x==yReturn 0If x>yReturn 1

Data type conversions

Python's built-in common functions also include data type conversion functions, such as int() functions that convert other data types to integers:

The function name is actually a reference to a function object, and it is possible to assign a function name to a variable, which is equivalent to giving the function an "alias":

>>> a = abs # 变量a指向abs函数>>> a(-1) # 所以也可以通过a调用abs函数1
In Python, you define a function to use the defstatement, which in turn writes out the function name, parentheses, arguments in parentheses, and colons :, and then, in the indent block, write the function body, and the return value of the function is returnStatement is returned. Notice that the statement inside the function body executes as soon as it executes to the return, the function finishes executing and returns the result. Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

Null function

If you want to define an empty function that does nothing, you can use a pass statement:

def nop():    pass

passWhat's the use of a statement that doesn't do anything? passit can actually be used as a placeholder, like the code that's not yet ready to write the function, so you can put one pass in place so the code can run.

passIt can also be used in other statements, such as:

if age >= 18:    pass

Is missing pass , the code runs with a syntax error.

Parameter check

When calling a function, if the number of arguments is incorrect, the Python interpreter automatically checks out and throws TypeError :

When an inappropriate parameter is passed in, the built-in function absParameter errors are checked, and we define the my_absThere is no parameter check, so this function definition is not perfect.

Let my_abs 's modify the definition, check the parameter type, and allow only integers and floating-point type parameters. Data type checking can be implemented with built-in functions isinstance :

def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError(‘bad operand type‘)    if x >= 0:        return x    else:        return -x
Return multiple values
import mathdef move(x, y, step, angle=0):    nx = x + step * math.cos(angle)    ny = y - step * math.sin(angle)    return nx, ny
>>> r = move(100, 100, 60, 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.

Default parameters

We still have a concrete example of how to define the default parameters for a function. Write a function to calculate the X2 first:

def power(x):    return x * x

When we call a power function, we must pass in the only one parameter x :

>>> power(5)25>>> power(15)225

Now, what if we're going to calculate x3? You can define a power3 function again, but if you want to calculate x4, X5 ... What to do? We cannot define an infinite number of functions.

You might think that you can power(x) change it to power(x, n) calculate xn and say dry:

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

For this modified power function, you can calculate the arbitrary n-th-square:

>>> power(5, 2)25>>> power(5, 3)125

However, the old calling code failed because we added a parameter that prevented the old code from being called properly:

>>> power(5)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: power() takes exactly 2 arguments (1 given)

At this point, the default parameters will come in handy. Since we often calculate x2, we can completely set the default value of the second parameter N to 2:

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

Thus, when we call power(5) , it is equivalent to calling power(5, 2) :

Defining default parameters Keep in mind that the default parameter must point to the immutable object!

Variable parameter variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.

The parameters of the function are changed to variable parameters:

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

When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with a * number. 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 parameter, including 0 parameters:

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

What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:

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

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

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

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

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

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

>>> person(‘Michael‘, 30)name: Michael age: 30 other: {}

You can also pass in any number of keyword parameters:

>>> person(‘Bob‘, 35, city=‘Beijing‘)name: Bob age: 35 other: {‘city‘: ‘Beijing‘}>>> person(‘Adam‘, 45, gender=‘M‘, job=‘Engineer‘)name: Adam age: 45 other: {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘}

What is the keyword argument for? It can extend the functionality of the function. For example, in a person function, we are guaranteed to receive name and both age parameters, but if the caller is willing to provide more arguments, we can receive them. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.

Similar to variable parameters, you can also assemble a dict, and then convert the dict into a keyword parameter:

>>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, city=kw[‘city‘], job=kw[‘job‘])name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}

Of course, the above complex invocation can be simplified:

>>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, **kw)name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
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

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

def func(a, b, c=0, *args, **kw):    print ‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw

At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument name.

>>> func(1, 2)a = 1 b = 2 c = 0 args = () kw = {}>>> func(1, 2, c=3)a = 1 b = 2 c = 3 args = () 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 through a tuple and dict, you can also call the function:

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

So, for any function, it can be called in a similar func(*args, **kw) way, regardless of how its arguments are defined.


Python Learning Notes _ one hour a day 8.24

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.