Learn Python's return to functions

  • 2020-04-02 14:15:04
  • OfStack

The basic structure of the function

Basic structure of functions in Python:


def The function name ([ The list of parameters ]):

      statements

  Some notes:
  The & # 8226; Function names should be named according to the naming requirements in python. Use lowercase letter and single underline, number to wait for combination commonly
  The & # 8226; So def is the beginning of the function, and it comes from the English word define, which is, of course, to define what
  The & # 8226; The function name is followed by a parenthesis, inside which you can have a list of arguments or no arguments
  The & # 8226; Don't forget the colon after the parenthesis
  The & # 8226; Statement, indent four Spaces relative to def, as is python custom

Take a look at a simple example and dig into the main points above:


>>> def name():         # Defines a function that takes no arguments, but is printed through the function
...     print "qiwsir"  # The indentation 4 A blank space
...
>>> name()              # Call the function, print the result
qiwsir >>> def add(x,y):       # Define a very simple function
...     return x+y      # The indentation 4 A blank space
...
>>> add(2,3)            # By the function 2+3
5

  Note that the add(x,y) function above does not specify the type of the parameters x and y. In fact, this sentence itself is wrong, remember the previous several times mentioned, in python, variables have no type, only objects have type, this sentence should be said: x,y does not strictly define the type of object it refers to.

Why is that? The column bits don't forget that the so-called parameters here are essentially the same thing as the variables mentioned earlier. You don't need to declare variables in advance in python; some languages do. The 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. So, in the add(x,y) function, x and y are completely free before they refer to the object, which means they can refer to any object, as long as the operation that follows permits, and if the operation that follows does not, it will report an error.


>>> add("qiw","sir")    # Here, x="qiw",y="sir" Let the function evaluate 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 and you will understand the error

  It is found from the experimental results 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 doesn't care about specific data types.

For the polymorphic problem in python, which you'll encounter later, this is just an example. Note that in python, interfaces are written for objects, not data types.

In addition, functions can also be referenced to a variable by an assignment statement:


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

  In this case, it actually explains one of the secrets of the function. Add (x, y) before being run, there is no such thing as in the computer, until the time of code to run here in the computer, has established an object, it's like previously studied a list of strings, and other types of objects, run the add (x, y), has also set up an add (x, y) of the object, the object and the variable result can reference relationship, and add the result (x, y) will return. Then, you can view the result of the operation through result.

If you read the above paragraph, feel a bit sweaty or dizzy, it doesn't matter, then read again. If you don't understand, don't do it. It will be understood as you go along.

Call a function

I've talked a lot about how to write functions, what's the point of writing functions? How do you call it in a program?

Why write a function? In theory, you can program without functions, and we've already written a program that guesses Numbers, so you don't write functions, and of course, python functions don't count. The main reason for using functions now is:
  1. To reduce the difficulty of programming, a large complex problem is usually broken down into a series of simpler small problems, and then the small problems are further divided into smaller problems. In order to realize this divide-and-conquer assumption, we need to write functions to break down the small problems one by one, and then gather them together to solve the big problems. (notice that the idea of divide and conquer is one of the most important ideas in programming.
  2. Use the code (chong, two sounds). In the process of programming, the same piece of code is more taboo to repeat, so you can define a function, in the program in multiple locations, can also be used for multiple programs. Of course, we'll come back to "modules" (which we've covered before, the thing we import), and you can put functions in a module for other programmers to use. You can also use functions defined by other programmers (such as import... , which is to apply a function written by someone else -- the person who created python. This avoids duplication of effort and provides efficiency.
 
So the function is necessary. Cut the crap and see how the function is called. Take add(x,y) as an example. The basic invocation method has been demonstrated earlier. In addition, you can:


>>> def add(x,y):       # This function is overridden to show the parameter assignment feature more clearly
...     print "x=",x    # Print the result of parameter assignment separately
...     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, the argument can either wait to be assigned, as before, or it can be assigned to a default value when it is defined. Such as:


>>> def times(x,y=2):       #y The default value 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,y The value of 2
x= 3
y= 4
12 >>> times("qiwsir")         # Once again, the polymorphic feature is shown
x= qiwsir
y= 2
'qiwsirqiwsir'

  Write the functions of adding, subtracting, multiplying and dividing two Numbers, and then use these functions to perform simple calculations.

Matters needing attention

The following are some common code writing considerations:
  1. Don't forget the colon. Remember to enter ":" at the end of the first line (if,while,for, etc.)
  2. Start with the first row. Make sure that the top-level (unnested) program code starts on the first line.
  3. Blank lines are important at interaction mode prompts. Blank lines in a module file that match statements are often ignored. However, when you type code at the interactive mode prompt, the blank line is the end of the statement.
  4. Indentation should be consistent. Avoid mixing tabs and Spaces in block indentation.
  5. Use a clean for loop instead of a while or range. The for loop is easier to write and runs faster
  6. Pay attention to mutable objects in assignment statements.
  7. Don't expect a function that changes in place to return a result, such as list.append()
  Be sure to call functions with parentheses
  9. Do not use extensions or paths in imports and reloads.


Related articles: