Python Learning Notes (9): function invocation and definition

Source: Internet
Author: User
Tags abs

Python to some extent and MATLAB is very similar, there are more built-in functions for users to call directly. Generally speaking, call functions need to know the name of the function and the parameters that need to be passed in, such as the absolute value function abs, you can view the help information of the ABS function through the interactive command line.
Call ABS function:

>>>abs (>100)
>>>abs ( -5)
>5

When calling a function, the system will complain if the incoming argument is incorrect.

Data type Conversions
Common functions built into Python typically include data type conversions, such as the Int () function, which converts a data type to an integer.

>>>int (' 123 ')
>123
>>>float (' 1.23 ')
>1.23
>str (1.23)
> ' 1.23 '
>bool (1)
>true

Han Shuming In fact, for a reference to a function object, you can use the following method to invoke the function by another name

>>>abs_new = ABS
>>>abs_new ( -1)
>1

Definition of function
As with other programming languages, users can define their own written functions, as shown in the figure below to define a simple operational function.

def my_function (x): Result
    = 5*x return result
    

The function's run result is returned using return, and if there is no return statement, the function returns the value none.
Functions can return multiple values that can be received with multiple variables, but functions return multiple values, usually in the form of tuple, which means that the function actually returns a tuple, and multiple variables can receive a tuple at the same time, assigning them by position. In the process of defining a function, you need to determine the name and number of parameters of the function.

parameter settings for a function

For users, when calling a function, you simply pass the correct arguments to the function, and the function is encapsulated inside, and the call is not understood. In addition to the required parameters, Python parameters can also use default parameters, variable parameters, and keyword parameters.

Default parameters
For example, to invoke the Python power () function, the default is to compute the square of the parameter, and if you calculate the cubic, four, five times of the parameter, you can define the function as follows.

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

After such a defined power () function, you can compute any n-times, but the power () function of the previous calculation of the square of the parameter cannot be used properly, because the previous function given a parameter that directly computes the square of the parameter. But after we have modified, the function requires a call to provide two parameters, this time we can use the default parameters to solve this problem, you can set the function of the second parameter default value of 2:

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

This definition of a function is invoked when power (4) is invoked, by default in call Power (4,2). But if you want to compute the other powers of the argument, you need to specify the parameters of the function.

When you use default parameters, there are a few things you should be aware of:
1 The required parameter of the function is in front, the default parameter is the following, because if the default parameter is before, the system will identify the second parameter you given as the given value of the first default parameter;
2 When the function is composed of multiple parameters, the variable parameters are placed in the front, and the small changes are put in the back.
The default parameter reduces the difficulty of invoking a function, and when complex calls are required, more parameters can be passed to implement without having to redefine the function. It is important to note, however, that the default parameters must only be immutable objects.

Variable parameters

In a Python function call, the number of arguments passed in is variable and can be any one. For example, given a set of numbers a,b,c ..., calculate the sum of its squares. To define this function, you must determine the input parameters and, because of the uncertainty of the parameters, you can use list to pass the parameters in, and the function can be defined as follows.

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

To invoke a function in this way, you need to define a list first.

>>>calc ([1,2,3])
>14

For a variable parameter of this function, you can use the following method.

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

When defining a variable parameter and defining a list parameter, only a * number is added before the parameter, and within the function, the parameter numbers receives a tuple. Therefore, the function code is completely unchanged, and when you call the function, you can pass in any argument, including 0 parameters.

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

Keyword parameters
Variable parameters allow you to 0 or any of the parameters that are automatically assembled into a tuple at the time of the call. Use keyword parameters that allow you to wear 0 or one parameter with a parameter name, which is automatically assembled into a dict within the function.

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

The function person also accepts the keyword parameter kw, in addition to the required parameter name and age, when the function is called, you can pass in only the required parameters, or you can 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 '}

You can extend the function by using keyword parameters, in the above example, to ensure that you receive the name and age two parameters, but you can also receive them if the caller provides more parameters.

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
>>> 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 = {}
>>> F UNC (1, 2, 3, ' A ', ' B ', x=99)
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {' X ': 99}
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.