Python study note _ 8.24 per hour per day

Source: Internet
Author: User

Python study note _ 8.24 per hour per day

8.24

 

Function

 

 

You can also usehelp(abs)ViewabsFunction help information.

Comparison Functions cmp(x, y)Two parameters are required. X , Return -1, If x==y, Return 0, If x>y, Return 1

 

Data Type Conversion

 

Common built-in functions of Python also include data type conversion functions, suchint()The function can convert other data types to integers:

The function name is actually a reference to a function object. You can assign the function name to a variable, which is equivalent to an alias for the function ":

>>> A = abs # variable a points to abs function >>> a (-1) # so you can call abs function 1 through.
In Python, define a function to use defStatement, 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 is returnStatement. Note that when executing a statement in the function body returnThe function is executed and the result is returned. Therefore, functions can implement complex logic through conditional judgment and loops.

 

Empty Function

 

If you want to define an empty function that does nothing, you can usepassStatement:

def nop():    pass

passThe statement does not do anything. What is the purpose? ActuallypassIt can be used as a placeholder. For example, you can putpassTo run the code.

passIt can also be used in other statements, such:

if age >= 18:    pass

MissingpassWhen the code is run, a syntax error occurs.

Parameter check

When calling a function, if the number of parameters is incorrect, the Python interpreter automatically checks the number and throwsTypeError:

When an inappropriate parameter is input, the built-in Function absWill check the parameter error, and my_absNo parameter check. Therefore, this function is not fully defined.

 

Let's modify it.my_absTo check the parameter type. Only parameters of the integer and floating point types are allowed. Built-in functions can be used for data type check.isinstanceImplementation:

def my_abs(x):    if not isinstance(x, (int, float)):        raise TypeError('bad operand type')    if x >= 0:        return x    else:        return -x
Returns 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, a tuple can be returned without parentheses, while multiple variables can receive a tuple at the same time and assign the corresponding value by position, A Python function returns a tuple, but it is easier to write.

 

Default parameters

 

The following example shows how to define the default parameters of a function. First, write a function to calculate x2:

def power(x):    return x * x

When we callpowerA function must be input with only one parameter.x:

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

What if we want to calculate x3? You can define anotherpower3Function, but if you want to calculate x4, x5 ...... What should I do? We cannot define an infinite number of functions.

You may have thoughtpower(x)Changepower(x, n)To calculate xn, just do it:

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

For the modifiedpowerFunction, which can calculate any nth power:

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

However, the old call Code fails because a parameter is added, which makes the old code unable to call normally:

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

In this case, the default parameters are used. Since we often calculate x2, we can 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

In this way, when we callpower(5)Is equivalent to callingpower(5, 2):

To define default parameters, remember that the default parameters must point to unchanged objects!

 

Variable parameters: the number of input parameters is variable, which can be 1, 2 to any, or 0.

 

Change the function parameter to a variable parameter:

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

 

Compared with defining the list or tuple parameter, defining variable parameters only adds*. Inside the function, the parameternumbersA tuple is received, so the function code remains unchanged. However, when calling this function, you can input any parameter, including 0 parameters:

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

If a list or tuple already exists, what should I do if I want to call a variable parameter? You can do this:

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

This method is feasible, and the problem is too cumbersome. Therefore, Python allows you to add*To change the list or tuple element to a variable parameter:

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

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. 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. See the example:

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

FunctionpersonExcept for required parametersnameAndageIn addition, keyword parameters are also accepted.kw. When calling this function, you can only input the required parameters:

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

You can also input 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 use of keyword parameters? It can expand functions of functions. For examplepersonIn the function, we ensure that we can receivenameAndageHowever, if the caller is willing to provide more parameters, we can also receive them. Imagine that you are working on a user registration function. Except that the user name and age are mandatory, other functions are optional. Using Keyword parameters to define this function can meet the registration requirements.

Similar to variable parameters, You can 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 calls can be simplified:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **kw)name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
Parameter combination

Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword parameter.

For example, defining a function includes the preceding four parameters:

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

When a function is called, the Python interpreter automatically transmits the corresponding parameters according to the parameter location and parameter 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 this function:

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

Therefore, for any functionfunc(*args, **kw)It is called, no matter how its parameters are defined.


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.