Python Tutorial - Functions

Python Exercise Lists

The application of functions in Python is very extensive. In the previous chapter, we have been exposed to multiple functions, such as the input, print, range, len functions, etc. These are all Python's built-in functions and can be used directly.

In addition to the built-in functions that can be used directly, Python also supports custom functions, that is, defining a regular, reusable code as a function, so as to achieve the purpose of writing once and calling multiple times.

For example, we learned the len function earlier, and we can directly obtain the length of a string. Let's imagine how to achieve the length of a string without the len function? Look at the following code:

n = 0
for i in "http://www.freelearningpoints.com/":
   n = n + 1
print (n)
           

The output is:

34

You know, getting the length of a string is a commonly used function, and it may be used many times in a program. If you write such a repeated code every time, it is not only time-consuming, labor-intensive, error-prone, but also cumbersome when giving it to others.

So, Python provides a function that allows us to encapsulate (wrap) commonly used code in a fixed format into an independent module. As long as you know the name of the module, you can reuse it. This module is called a function.

For example, a piece of code is defined in a program, and this code is used to implement a specific function. Here comes the question. If you need to implement the same function next time, do you want to copy the code defined earlier? It means that every time the program needs to implement the function, it must copy the previously defined code once. The correct approach is to define the code that implements a specific function as a function, and whenever the program needs to implement the function, it only needs to execute (call) the function.

In fact, the essence of a function is a piece of code that has specific functions and can be reused. This code has been written in advance and has a "good" name for it. In the subsequent process of writing the program, if the same function is needed, this code can be called directly by a good name.

Here's how to encapsulate the len function we implemented into a function:

#Custom len function
def my_len (str):
    length = 0
    for c in str:
       length = length + 1
    return length
#Call the custom my_len function
length = my_len ("http://www.freelearningpoints.com/")
print (length)
#Call my_len function again
length = my_len ("http://www.freelearningpoints.com/")
print (length)
           

The output is:

34
34

If the reader has been exposed to functions in other programming languages, the above description of functions is certainly not unfamiliar. But it should be noted that, like functions in other programming languages, Python functions support receiving multiple (≥0) parameters. The difference is that Python functions also support returning multiple (≥0) values.

For example, in the above program, the my_len (str) function we encapsulated by ourselves. When we defined this function, we set a str parameter for it. At the same time, the function internally returns a length value.

It is not difficult to see from the example of the my_len function that the use of the function is roughly divided into two steps, namely defining the function and calling the function. The next one will explain in detail for the reader.

Definition of Python Functions

Defining a function, that is, creating a function, can be understood as creating a tool with some uses. Defining functions needs to be implemented with the def keyword. The specific syntax is as follows:

def function name (parameter list):
    // Multi-line code to achieve a specific function
    [return [return value]]
           

Among them, [] is an optional part, which can be used or omitted.

The meanings of the parameters in this format are as follows:

  • Function name: In fact, it is an identifier that conforms to the syntax of Python. However, readers are not recommended to use simple identifiers such as a, b, and c as function names. The function name should better reflect the function of the function (such as my_len (Meaning our custom len function).
  • Formal parameter list: Set how many parameters the function can receive. Multiple parameters are separated by commas (,).
  • [return [return value]]: The optional parameter of the function is used to set the return value of the function. In other words, a function can have a return value or no return value. Whether it needs to be determined according to the actual situation.

Note that when creating a function, you must keep an empty pair of "()" even if the function does not require parameters, otherwise the Python interpreter will prompt an "invalid syntax" error. Alternatively, if you want to define an empty function without any functionality, you can use the pass statement as a placeholder.

For example, two functions are defined below:

#Defining an empty function, has no practical meaning
def pass_dis ():
    pass
#Define a function that compares the size of a string
def str_max (str1, str2):
    str = str1 if str1> str2 else str2
    return str
           

Although the Python language allows you to define an empty function, the empty function itself has no practical meaning.

It is also worth mentioning that the return statement in the function can directly return the value of an expression, for example, modify the str_max () function above:

def str_max (str1, str2):
    return str1 if str1> str2 else str2
           

The function of this function is exactly the same as the str_max () function above, except that the creation of the str variable is omitted, so the function code is more concise.

Python function calls

Calling a function means executing it. If the created function is understood as a tool with a certain purpose, then calling the function is equivalent to using the tool.

The basic syntax of a function call is as follows:

[Return value] = function name ([formal parameter value])

Among them, the function name refers to the name of the function to be called; the formal parameter value refers to the value of each formal parameter required to be passed in when the function is initially created. If the function has a return value, we can receive the value through a variable, but of course we cannot accept it.

It should be noted that as many parameters as the function is created, how many values need to be passed in when calling, and the order must be the same as when the function is created. Even if the function has no parameters, the parentheses after the function name cannot be omitted.

For example, we can call the pass_dis and str_max functions created above:

pass_dis ()
strmax = str_max ("http://www.freelearningpoints.com/python", "http:// www.freelearningpoints.com /shell");
print (strmax)
           

First of all, for calling an empty function, since the function itself does not contain any valuable execution code and has no return value, calling an empty function should have no effect.

Secondly, for the str_max () function called in the above program, since the function was originally defined with 2 parameters set for it, so when calling this parameter, you must pass in 2 parameters. At the same time, because the function also uses a return statement, we can use the strmax variable to receive the return value of the function.

Therefore, the program execution result is:

http://www.freelearningpoints.com/python

Provide Documentation for Python Functions

As mentioned in the previous chapter, by calling Python's help built-in function or __doc__ attribute, we can view the documentation of a function. In fact, whether it is a function provided to us by Python or a custom function, its documentation needs to be written by the programmer who designed the function.

In fact, the function documentation is essentially a string of characters, but as a description document, the placement of the string is particular. The function documentation is usually located inside the function and at the front of all code.

In fact, the function documentation is essentially a string of characters, but as a description document, the placement of the string is particular. The function documentation is usually located inside the function and at the front of all code.

Taking the str_max () function in the above program as an example, the following shows how to set up documentation for it:

#Define a function that compares the size of a string
def str_max (str1, str2):
    '''
    Compare the size of 2 strings
    '''
    str = str1 if str1> str2 else str2
    return str
help (str_max)
#print (str_max .__ doc__)
           

The program execution result is:

Help on function str_max in module __main__:
str_max(str1, str2)
   Compare the size of 2 strings

In the above program, you can also use the __doc__ attribute to get the documentation of the str_max () function, that is, the output statement of the last line is used, and the output is

Python Function - Value Passing and Reference Passing

Generally, when defining a function, a function form with parameters is selected. The function of the function parameters is to pass data to the function, so that it can perform specific operations on the received data.

When using functions, formal parameters (referred to as "formal parameters") and actual parameters (referred to as "actual parameters") are often used. Both are called parameters. The difference between them is:

Formal parameters: When defining a function, the parameters in parentheses after the function name are formal parameters, for example:

#When defining a function, the function parameter obj here is a formal parameter
def demo(obj):
    print(obj)
           

Actual parameters: When a function is called, the parameters in parentheses after the function name are called actual parameters, that is, the parameters given to the function by the caller of the function. Example:

a = "Python Language Website"
#Call the defined demo function, and the function parameter a passed in at this time is the actual parameter
demo (a)
           

The output is:

Python Language Website

The difference between actual parameters and formal parameters is like the main character of the script. The role of the script is equivalent to the formal parameter, and the actor who plays the role is equivalent to the actual parameter.

Now that you understand what formal and actual parameters are, let's think about another question: how are actual parameters passed to formal parameters?

In Python, according to the type of the actual parameter, there are two ways to pass function parameters, which are value passing and reference (address) passing:

  • Value passing: applicable to the type of the immutable type (string, number, tuple);
  • Reference (address) passing: applicable to the type of the argument is variable (list, dictionary);

The difference between value passing and reference passing is that after the function parameter is passed by value, if the value of the formal parameter is changed, it will not affect the value of the actual parameter; while the function parameter continues to pass by reference, the value of the formal parameter is changed, and the value of the actual parameter It will change together.

For example, define a function named demo that passes in a variable of type string (for value passing) and a variable of list type (for passing by reference):

def demo (obj):
    obj += obj
    print ("Form parameter value:", obj)
print ("------- value passing -----")
a = "Python Language Website"
print ("The value of a:", a)
demo (a)
print ("Argument value:", a)
print ("----- pass by reference -----")
a = [1,2,3]
print ("The value of a:", a)
demo (a)
print ("Argument value:", a)
           

The output is:

------- value passing -----
The value of a: Python Language Website
Form parameter value: Python Language WebsitePython Language Website
Argument value: Python Language Website
----- pass by reference -----
The value of a: [1, 2, 3]
Form parameter value: [1, 2, 3, 1, 2, 3]
Argument value: [1, 2, 3, 1, 2, 3]

It is not difficult to see the results of the analysis. When the value of the formal parameter is changed when the value is passed, the actual parameter will not change. When the value of the formal parameter is changed by reference, the actual parameter will also be changed.

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises