With the old Ziko python return function _python

Source: Internet
Author: User
Tags stdin in python

The basic structure of a function

The basic structure of functions in Python:

Copy Code code as follows:

def function name ([parameter list]):

Statement

A few notes:
• The naming rules for function names conform to the naming requirements in Python. General use of lowercase letters and single underline, numbers and other combinations
def is the beginning of a function, this shorthand comes from the English word define, obviously, is to define something
• The function name is followed by parentheses, which can have a parameter list or no parameters
• Never forget the colon behind the brackets
• Statement, indented with Def, indent four spaces according to Python custom

Look at the simple examples to understand the main points above:

Copy Code code as follows:

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

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

Notice the Add (x,y) function above, in which there is no particular type of parameter x,y. In fact, this sentence itself is wrong, remember that in the previous mentioned many times, in Python, variables are not type, only objects have type, this sentence should be said: X,y does not strictly specify the type of object it refers to.

Why? Do not forget that the so-called parameters here, with the variables mentioned above, are essentially the same thing. In Python, there is no need to declare variables in advance, and some languages need to be declared. It is only when the variable is used that the corresponding relationship between the variable and the object is established, otherwise the relationship is not established. objects have different types. Then, in the Add (x,y) function, X,y is completely free before referencing objects, that is, they can refer to any object, as long as the subsequent operation permits, if the subsequent operation is not allowed, then the error.

Copy Code code as follows:

>>> Add ("Qiw", "Sir") #这里, x= "Qiw", y= "sir", let function calculation 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 #仔细阅读报错信息 to understand the error.

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, code doesn't care about a particular data type.

For the polymorphic problem in Python, you'll encounter it later, just to show it in this example. Reader to be careful: you write an interface for an object in Python, not a data type.

Alternatively, you can establish a reference relationship with a variable through an assignment statement:

Copy Code code as follows:

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

Here, in fact, explains the function of a secret. Add (X,y) before being run, the computer does not exist, until the code runs here, in the computer, the establishment of an object, as in the previous study of the string, list, and other types of objects, run Add (x,y) after the creation of an Add (x,y) Object, this object can establish a reference relationship with the variable result, and add (x,y) returns the results of the operation. Results can then be viewed by result.

If the reader above a paragraph, feel a little hard or dizzy, it does not matter, then read one side. If you don't understand it, don't do it. As the study progresses, it will be understood.

Call function

How do you write a function by pulling a lot of functions? How do you call it in the program?

Why write a function? Theoretically, without functions, we can also program, we have already written a number of guesses in the previous program, there is no write function, of course, with the Python function does not calculate. The main reason for using functions now is:
1. Reducing the difficulty of programming often breaks down a complex big problem into a series of simpler little problems, and then divides the small problem into smaller problems that can be divided when the problem is refined to be simple enough. In order to realize this idea of divide and conquer, we should write function to break each small problem one by one, and then gather together to solve the big problem. (Reader note that the idea of divide and conquer is an important idea of programming, and the so-called "divide and conquer" method. )
2. Code heavy (Chong, two sound) use. In the process of programming, it is 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 for multiple programs. Of course, we'll go back to the "module" (which is also related to the import of imports), and you can put the function in a module for other programmers to use. You can also use other programmer-defined functions, such as import ..., which has been used before, that is, to apply someone else-the person who created Python-the written function. This avoids duplication of effort and provides efficiency.

In this sense, the function is still very necessary. Talk less, then see the function how to call it. Take Add (x,y) as an example, the basic invocation method has been demonstrated earlier, and you can also do this:

Copy Code code as follows:

>>> def Add (x,y): #为了能够更明了显示参数赋值特点, overriding 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 you define a function, the arguments can be like the one before, waiting to be assigned, or assigning a default value when defined. For example:

Copy 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 =3,y=4,y value is no longer 2
X= 3
Y= 4
12

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

To all of you reader a study questions, please use Python to complete: write two number of add, subtract, multiply, divide the function, and then use these functions, complete a simple calculation.

Attention matters

The following are a few things to note about common code writing:
1. Don't forget the colon. Be sure to remember to enter ":" (first line of if,while,for, etc.) at the end of the first line of the statement
2. Start with the first line. To determine that the top-level (no nested) program code starts at the first line.
3. Blank lines are important at the interactive mode prompt. The blank lines within the module file that conform to the statement are often ignored. However, when you enter code at the interactive mode prompt, the blank line ends the statement.
4. Indentation should be consistent. Avoid mixing tabs and spaces in block indents.
5. Use a concise for loop instead of a while or range. The For loop is easier to write and faster to run than
6. Be aware of the Mutable object in the assignment statement.
7. Do not expect the function modified in situ will 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.