With old Ziko Python's return function

Source: Internet
Author: User
Tags naming convention
basic structure of a function

The basic structure of a function in Python:
Copy the Code code as follows:


def function name ([parameter list]):

Statement

A few notes:
• The naming convention for function names conforms to the naming requirements in Python. General use of lowercase letters and single underline, numbers and other combinations
def is the beginning of the function, and this shorthand comes from the English word define, which clearly defines a thing.
• The function name is followed by parentheses, inside the parentheses, with a parameter list, or without parameters
• Never forget the colon after the parentheses
• A statement that indents four spaces in Python, as opposed to the Def indent

Look at a simple example to get a deeper understanding of the above points:
Copy the Code code as follows:


>>> def name (): #定义一个无参数的函数, just print through this function
... print "Qiwsir" #缩进4个空格
...
>>> name () #调用函数, printing results
Qiwsir

>>> def add (x, y): #定义一个非常简单的函数
... return X+y #缩进4个空格
...
>>> Add (2,3) #通过函数, calculate 2+3
5

Note that the add (x, y) function above, in this function, does not specifically specify the type of parameter x, Y. In fact, this sentence itself is wrong, remember that in the previous has been mentioned many times, in Python, the variable is no type, only the object has a type, this sentence should be said: X, y does not strictly specify the type of object it refers to.

Why? Yours faithfully do not forget that the so-called parameters here, with the variables mentioned earlier, are essentially one thing. In Python there is no need to declare variables in advance, and some languages need to be declared. The corresponding relationship between the variable and the object is established only when the variable is used, otherwise the relationship is not established. objects have different types. Then, in the Add (x, y) function, x, Y is completely free before referencing the object, that is, they can refer to any object, as long as the subsequent operation permits, if the subsequent operation is not permitted, then an error will be given.
Copy the Code code as follows:


>>> Add ("Qiw", "Sir") #这里, x= "Qiw", y= "Sir", let the function calculate x+y, i.e. "QIW" + "sir"
' Qiwsir '

>>> Add ("Qiwsir", 4)
Traceback (most recent):
File " ", line 1, in
File " ", line 2, in Add
Typeerror:cannot concatenate ' str ' and ' int ' objects #仔细阅读报错信息, you know the wrong place.

From the experimental results, it is found that the meaning of x+y depends entirely on the type of object. 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 a particular data type.

For a polymorphic problem in Python, you will encounter it later, just to show it in this example. Please crossing to note: Python writes an interface for an object, not a data type.

In addition, you can use a function to establish a reference relationship with a variable through an assignment statement:
Copy the Code code as follows:


>>> result = Add (3,4)
>>> result
7

Here, in fact, explains a secret of the function. Add (x, y) is not present in the computer until the code runs here, and an object is created on the computer, just like the string, list, and other types of objects previously learned, and an add (x, y) is created after running Add (x, y) object, this object and the variable result can establish a reference relationship, and add (x, y) returns the result of the operation. As a result, you can view the results of the operation by using result.

If crossing above paragraph, feel a bit of difficulty or dizzy, also does not matter, then read one side again. If you don't understand, don't do it. As the study progresses, it will be understood.

Calling functions

What's the use of writing a function when you've pulled a lot of functions? How do I call it in the program?

Why write a function? Theoretically, without the function, we can also program, we have written a guessing number in front of the program, there is no write function, of course, with the function of Python do not forget. The main reason for using functions now is:
1. Reduce the difficulty of programming, usually a complex big problem into a series of more simple small problems, and then continue to divide small problems into smaller problems, when the problem is refined enough simple, you can divide and conquer. In order to realize this idea of divide and conquer, it is necessary to write a function to break each small problem one by one, then assemble it to solve the big problem. (Crossing note that the idea of divide and conquer is an important idea of programming, so-called "divide and Conquer" method. )
2. Code weight (Chong, two voices) with. In the process of programming, it is more taboo to repeat the same piece of code, so you can define a function that can be used in multiple locations in a program, or in multiple programs. Of course, we will also talk about the "module" (which is also involved in the import of imports), you can also put the function in a module for other programmers to use. You can also use other programmer-defined functions, such as import ..., which are already used, that is, the person who created Python--the function that was written--was applied. This avoids duplication of effort and provides efficiency.

In this sense, the function is still necessary. Talk less, and see how the function is called. With Add (x, y) as an example, the basic invocation method has been shown earlier, and you can do this:
Copy the Code code as follows:


>>> def add (x, y): #为了能够更明了显示参数赋值特点, override this function
... print "x=", x #分别打印参数赋值结果
... print "y=", y
... return X+y
...
>>> Add (10,3) #x =10,y=3
x= 10
Y= 3
13
>>> Add (x=10,y=3) #同上
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, the parameter can be assigned to a default value as before, waiting for the value to be assigned, or to be defined. For example:
Copy the Code code as follows:


>>> def Times (x,y=2): #y的默认值为2
... print "x=", X
... print "y=", y
... return X*y
...
>>> times (3) #x =3,y=2
X= 3
Y= 2
6

>>> times (x=3) #同上
X= 3
Y= 2
6

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

>>> Times ("Qiwsir") #再次体现了多态特点
x= Qiwsir
Y= 2
' Qiwsirqiwsir '

To yours faithfully crossing a study questions, please do in your spare time with Python: write two number of add, subtract, multiply, divide functions, and then use these functions to complete a simple calculation.

Precautions

The following are some of the common considerations for writing code:
1. Don't forget the colon. Be sure to remember to enter ":" At the end of the first line of the statement (first line of if,while,for, etc.)
2. Start with the first line. To determine the top level (no nesting) program code starts at the first line.
3. Blank lines are important at the interactive mode prompt. A blank line within a module file that conforms to a statement is often overlooked. However, when you enter code at the interactive mode prompt, the blank line is the end statement.
4. Indent to be consistent. Avoid mixing tabs and spaces in block indentation.
5. Use a simple for loop instead of a while or range. The For loop is easier to write and faster to run than
6. Be aware of mutable objects in assignment statements.
7. Do not expect the function to be modified in situ to return results, such as list.append ()
8. Be sure to call the function with parentheses
9. Do not use extensions or paths in imports and overloads.

  • 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.