Linux under Python learning Note 3: Functions

Source: Internet
Author: User

First, what is a function

The function is simple to understand is the number according to a certain rule repeating rules, we know the area of the circle calculation formula is: S =πr², when we know the radius r value, we can calculate the area according to the formula. In programming, the function is further encapsulated as a method, receiving an externally passed parameter to bring in the rule, and returning the corresponding result. The encapsulation of that method is actually an abstract result.

Abstraction is a very common concept in mathematics. As an example:

Calculate the sum of the series, such as:1 + 2 + 3 + ... +, writing is very inconvenient, so mathematicians invented the summation symbol ∑, can be 1 + 2 + 3 + ... + 100:

100∑nn=1

This abstract notation is very powerful, because we see that ∑ can be understood as sums, rather than reduced to lower-level addition operations.

Moreover, this abstract notation is extensible, such as:

100∑ (n²+1) n=1

The reduction into the addition operation becomes:

(1 x 1 + 1) + (2 x 2 + 1) + (3 x 3 + 1) + ... + (x 100 + 1)

It can be seen that, with the help of abstraction, we do not care about the underlying computational process, but directly consider the problem at a higher level.

The same is true of computer programs, where functions are the most basic form of code abstraction.

Python is not only very flexible in defining functions, but it has built in many useful functions that can be called directly.

 
 
Second, call the function

Python has built in a lot of useful functions that we can call directly. To invoke a function, you need to know the name and parameters of the function , such as an absolute function abs, which receives a parameter.

Documents can be viewed directly from the official website of Python: http://docs.python.org/2/library/functions.html#abs

You can also view the Help information for the ABS function on the interactive command line by helping (ABS).

Call the abs function:

When calling a function, if the number of arguments passed in is incorrect, the TypeError error is reported, and Python will explicitly tell you that ABS () has only 1 parameters, but gives two:

If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, the TypeError error is reported, and an error message is given: STR is the wrong parameter type:

The comparison function cmp (x, y) requires two parameters, if x<y, returns 1, if x==y, returns 0, if x>y, returns 1:

Python's built-in common functions also include data type conversion functions, such as the Int () function, which converts other data types to integers:

The STR () function converts other types to str:

The sum () function can accumulate:

There are, of course, more general-purpose functions that can be consulted when used in detail.

Third, write the function

In Python, define a function to use the def statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

Let's take the example of a custom my_abs function that asks for an absolute value:

note that when the statement inside the function body executes, once it executes to return, the function finishes and returns the result. Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

If there is no return statement, the result is returned after the function is executed, except that the result is none.

Return none can be shortened to return.

Four, return multi-value

Can a function return multiple values? The answer is yes.

For example, in the game often need to move from one point to another point, give the coordinates, displacements and angles, you can calculate the new coordinates:

# The Math package provides the sin () and cos () functions, which we first refer to with import:

But in fact it's just an illusion, the Python function returns a single value, and we use a variable to receive it:

It is found that a tuple is returned, but, in syntax, returning a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, assigning the corresponding value by location, so that thepython function Returns a multivalued value is actually the return of a tuple , but it is more convenient to write.

Write a function that returns a unary two-second equation: ax²+ bx + c = 0 of two solutions:

After root x = (-b±√ (B²-4AC))/2a

V. Recursive functions

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n) , you can see:

Fact (n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact (n-1) * n

So,fact (n) can be represented as N * Fact (n-1), and only n=1 requires special handling.

So, fact (n) is written in a recursive way:

If we calculate the fact (5), we can see the calculation process according to the function definition as follows:

===> fact (5) ===> 5 * FACT (4) ===> 5 * (4 * FACT (3)) ===> 5 * (4 * (3 * FACT (2))) ===> 5 * (4 * (3 * (2 * FACT ( 1))) ===> 5 * (4 * (3 * (2 * 1))) ===> 5 * (4 * (3 * 2)) ===> 5 * (4 * 6) ===> 5 * 24===> 120

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try to calculate fact (10000).

Vi. Defining Default Parameters

When defining a function, you can also have default parameters.

For example, the python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:

The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.

As you can see, the function's default parameter is to simplify the call , and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

Let's define a function that calculates the n-th square of x:

You can see that the default value is 2, and that just passing in X when called is equivalent to x ².

As with other languages, default parameters can only be defined after the non-required parameters.

Vii. Defining variable Parameters

If you want a function to accept any of the arguments, we can define a variable parameter:

 
  

There is an * number in front of the variable parameter, we can pass 0, one or more parameters to the variable parameter:

Mutable parameters are also not very mysterious, the Python interpreter will assemble a set of parameters passed into a tuple to the variable parameters, so, inside the function, the variable args directly as a tuple is good.

The purpose of defining mutable parameters is also to simplify the invocation. Suppose we want to calculate an arbitrary number of averages, we can define a variable parameter:

Linux under Python learning Note 3: Functions

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.