Returning to the function of learning Python with the old man, the heavy lifting of learning python

Source: Internet
Author: User

Returning to the function of learning Python with the old man, the heavy lifting of learning python

Basic Function Structure

Basic Structure of functions in Python:
Copy codeThe Code is as follows:
Def function name ([parameter list]):

Statement

Notes:
• The naming rules of function names must comply with the naming requirements in python. Generally, it is composed of lowercase letters, single underscores, and numbers.
• Def is the beginning of a function. This abbreviation comes from the English word define. Obviously, it is to define something.
• Function names are followed by parentheses, which can contain a list of parameters or no parameters.
• Do not forget the colon following the parentheses
• The statement is Indented by four spaces according to the python conventions.

Let's take a look at a simple example to get a deeper understanding of the above points:
Copy codeThe Code is as follows:
>>> Def name (): # define a function without parameters, just print it through this function
... Print "qiwsir" # indent four spaces
...
>>> Name () # Call the function and print the result
Qiwsir

>>> Def add (x, y): # define a very simple function.
... Return x + y # indent 4 spaces
...
>>> Add (2, 3) # Calculate 2 + 3 using functions
5

Note that the preceding add (x, y) function does not specify the types of x and y. In fact, this sentence is itself wrong. I still remember that in python, variables have no type and only objects have types. This sentence should be said: x and y do not strictly specify the object types they reference.

Why? Do not forget the column bit. The so-called parameter here is essentially the same as the variable mentioned above. In python, variables do not need to be declared in advance, and some languages need to be declared. Only when this variable is used can the corresponding relationship between the variable and the object be established. Otherwise, the relationship is not established. Objects have different types. In the add (x, y) function, x and y are completely free before they reference objects, that is, they can reference any object, as long as the subsequent operation permits, if the subsequent operation is not permitted, an error is reported.
Copy codeThe Code is as follows:
>>> Add ("qiw", "sir") # Here, x = "qiw", y = "sir", let the function compute x + y, that is, "qiw" + "sir"
'Qiwsir'

>>> Add ("qiwsir", 4)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in add
TypeError: cannot concatenate 'str' and 'int' objects # Read the error message carefully to understand the error.

The experiment shows that the meaning of x + y depends on the object type. In python, this dependency is called polymorphism. This is an important difference between python and other static languages. In python, the Code does not care about specific data types.

The problem of polymorphism in python will be encountered in the future. Here we only show it in this example. Note: In python, write interfaces for objects instead of data types.

In addition, you can use a value assignment statement to establish a reference relationship with a variable:
Copy codeThe Code is as follows:
>>> Result = add (3, 4)
>>> Result
7

Here, we actually explain a secret of the function. Add (x, y) does not exist in the computer until the code runs here, and an object is created in the computer, this is like the previously learned string, list, and other types of objects. After running add (x, y), an add (x, y) object is created, this object can establish a reference relationship with the result variable, and add (x, y) returns the operation result. Therefore, you can view the operation result through result.

If you feel a little hard or dizzy when you look at the previous section of the official website, it doesn't matter. Then read it again. If you don't understand it, don't do it. As learning goes deeper, it will be understood.

Call a function

How to write a lot of functions? What is the purpose of writing a function? How can I call it in a program?

Why write a function? Theoretically speaking, we can program without using functions. We have already written a program to guess numbers, so we have not written a function. Of course, the python function cannot be used. Currently, the main reasons for using functions are:
1. to reduce the difficulty of programming, a complex big problem is usually divided into a series of simpler small problems, and then small problems are further divided into smaller problems. When the problem is refined to simple enough, you can divide and conquer it. To achieve this divide and conquer, We Need To Write Functions to break down small problems one by one and then combine them to solve big problems. (Please note that the idea of divide and conquer is an important idea of programming. The so-called "divide and conquer" method also applies .)
2. chong (two voices. In the process of programming, it is more taboo to repeatedly repeat the same piece of code. Therefore, you can define a function and use it in multiple places of the program. It can also be used in multiple programs. Of course, we will also talk about the "module" (previously involved, that is, the import thing). We can also put functions in a module for other programmers to use. You can also use functions defined by other programmers (such as import..., which has been used before, that is, to apply the functions written by others-the python creator ). This avoids repetitive work and provides work efficiency.
 
In this case, the function is necessary. Let's just talk about how to call a function. Taking add (x, y) as an example, we have demonstrated the Basic Call method. In addition, we can also do this:
Copy codeThe Code is as follows:
>>> Def add (x, y): # rewrite this function to better display the parameter assignment features.
... Print "x =", x # print the parameter assignment results respectively.
... Print "y =", y
... Return x + y
...
>>> Add (10, 3) # x = 10, y = 3
X = 10
Y = 3
13
>>> Add (x = 10, y = 3) # Same as above
X = 10
Y = 3
13
>>> Add (y = 10, x = 3) # x = 3, y = 10
X = 3
Y = 10
13
>>> Add (3,10) # x = 3, y = 10
X = 3
Y = 10
13

When defining a function, you can assign a default value to a parameter that is waiting to be assigned a value. For example:
Copy codeThe Code is as follows:
>>> Def times (x, y = 2): # The default value of y is 2.
... Print "x =", x
... Print "y =", y
... Return x * y
...
>>> Times (3) # x = 3, y = 2
X = 3
Y = 2
6

>>> Times (x = 3) # Same as above
X = 3
Y = 2
6

>>> Times (3, 4) # x = 3, y = 4. The value of y is no longer 2.
X = 3
Y = 4
12

>>> Times ("qiwsir") # It reflects the characteristics of polymorphism again
X = qiwsir
Y = 2
'Qiwsirqiwsir'

I would like to give a thinking question to the column viewer. Please use python in your spare time: Write the functions for adding, subtracting, multiplication, and division of two numbers, and then use these functions to complete simple computing.

Notes

The following are some common notes for coding:
1. Don't forget the colon. Remember to enter ":" at the end of the first line of the statement (if, while, for, etc)
2. Start from the first line. Determine that the top-level (non-nested) program code starts from the first line.
3. blank lines are very important in interactive mode prompt. The blank lines in the module files that conform to the statement are often ignored. However, when you enter code at the interactive mode prompt, a blank line will end the sentence.
4. the indentation must be consistent. Avoid mixing tabs and spaces in block indentation.
5. Use a concise for loop instead of a while or range. Compared to a for loop, it is easier to write and run faster.
6. Pay attention to variable objects in the value assignment statement.
7. Do not expect the function modified in the original to return results, such as list. append ()
8. Be sure to use brackets to call functions.
9. Do not use the extension or path in import and reload.


Python calls another function at the end of the Function

The question you asked is whether python supports tail call elimination, that is, whether to save the original function stack when calling other functions in the last sentence to save memory.
Remember that native python does not support it and requires special libraries.
This is generally supported by functional languages.

Explain the execution process of this Python Function

It is indeed recursive. When executing the command, one yield is passed to another yield, which seems inefficient.
This is similar to the example given at the end of this article:
Www.ibm.com/..rm-20/

In other words, listing = [I for I in fun] seems to be a List = List (fun)

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.