Python function basics

Source: Internet
Author: User

Function basics

Simply put, a function is a combination of a set of Python statements that can run one or more times in a program. Functions in Python are also called procedures or subroutines in other languages, and these wrapped statements are called by a function name.

With the function, we can greatly reduce the number of copies and paste of the code (I believe many people have this experience at first). We can extract the same code to make a function, where it needs to be called only. Then, this increases the code reuse rate, the overall code looks relatively concise, not so bloated.

Functions are the most basic program structure in Python to maximize the reuse of our code, while functions can divide a complex system into manageable parts, simplifying programming and code reuse.

Next we look at what the function is and how it is defined. There are two ways to define a function, respectively, def and a lambda keyword.

function definition

Let's summarize why we use functions.

    1. Maximize code reuse and minimize redundant code;
    2. Process decomposition (disassembly). Disassemble a complex task into multiple small tasks.

The syntax for a function definition is ( def a function object is created with the keyword, and the object is assigned a value to a function name.) ):

def func_name(arg1, arg2, arg3, ..., argN):    statement    return value

As defined above, it can be simply described as: a function in Python is a block of statements (note indentation) that has 0 or more parameters, has several line statements, and has a return value (the return value is optional).

Then we define a simpler function that has no parameters and enters the Ipython interactive environment:

In [1]: def hello():  ...:    print(‘Leave me alone, the world‘)  ...:

defStatement defines a function, but it does not call the function. We can call the defined function in the code, add a pair of parentheses after the function name, and the parentheses have optional function arguments. The function is then called (executed).

In [2]: hello()Leave me alone, the world

We find that the hello() function does not have a return statement, in Python, if there is no explicit execution of the return statement, then the return value of the function defaults to None .

As we have said, there are two forms of defining a function, and the other is defined using it lambda . Using a lambda defined function is an anonymous function, and this is what we'll be explaining in a later section, not a table.

Now let's take a look at a function definition with parameters and call:

>>> def intersect(seq1, seq2):...    res = []...    for x in seq1:...        if x in seq2:...            res.append(x)...    return res... >>> s1 = ‘SPAM‘>>> s2 = ‘SCAM‘>>> intersect(s1, s2)[‘S‘, ‘A‘, ‘M‘]

The main function of this example is to pass in two lists and ask for their common elements. When we call this function, we need to pass two parameters to this function. Here we pass the S1 to the seq1 in the function body, pass the S2 to the SEQ2, and return the return value res to the caller. We did not receive the return value of the function in the above demo, and if we need to use the return value of the function in the following code, we can assign the return value of the function to a variable. Such as:

>>> result = intersect(s1, s2)>>> result[‘S‘, ‘A‘, ‘M‘]

For the example above, you can use the list deduction described in the previous article:

>>> [x for x in s1 if x in s2][‘S‘, ‘A‘, ‘M‘]
function combat

The basic function is introduced here, the next practical small example, through the requests library to query the location of mobile phone number attribution information. If the system does not have a requests package installed, use PIP or Easy_install to install:

pip install requests

The code is (the code executed in the Ipython Interactive environment):

In [1]: import requestsIn [2]: def phone():   ...:     num = input(‘Enter your phone number>>> ‘)   ...:     api = ‘http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=‘   ...:     r = requests.get(api + num.strip())   ...:     if r.ok:   ...:         print(r.text)   ...:     r.close()   ...:     return None   ...: In [3]: phone()Enter your phone number>>> 13651813235__GetZoneResult_ = {    mts:‘1365181‘,    province:‘上海‘,    catName:‘中国移动‘,    telString:‘13651813235‘,areaVid:‘29423‘,ispVid:‘3236139‘,carrier:‘上海移动‘}

The function in the example above does not receive parameters, then the function is transformed into a parameter. The code is:

In [4]: def phone(phone_num):   ...:     api = ‘http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=‘   ...:     res = requests.get(api+phone_num)   ...:     if res.ok:   ...:         print(res.text)   ...:     res.close()   ...:     return None   ...: In [5]: phone(‘13651813235‘)__GetZoneResult_ = {    mts:‘1365181‘,    province:‘上海‘,    catName:‘中国移动‘,    telString:‘13651813235‘,areaVid:‘29423‘,ispVid:‘3236139‘,carrier:‘上海移动‘}
Summary: Function design principles
    • Coupling:use arguments for inputs and return for outputs
    • Coupling:use Global variables only when truly necessary
    • Coupling:don ' t change mutable arguments unless the caller expects it
    • Cohesion:each function should has a single, unified purpose
    • Size:each function should be relatively small
    • Coupling:avoid changing variables in another module file directly

Python function basics

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.