python learning -- functions

Function function

There is a saying that mathematics is the language of the universe. The main reason should be the function. Thousands of people in the world can be expressed by a function. In python, a function can be understood as packaging a series of operations. When you call the function, the program will execute all the statements in the function.

Classification of functions

When it comes to functions, you should think of the familiar f(x). Functions in programming languages are not much different from functions in mathematics. In the programming language, it can be divided into functions with return value and functions without return value, including parametric functions and nonparametric functions.
When we use a function, it will be divided into two parts: the definition of the function and the call of the function.

Nonparametric function

In python, we use the def statement to tell the computer that all the indented contents below are the functions I am defining.

1. No return value

def hello():
    print("hello this is python")

This is the definition of a function. When the program runs, the content in the function definition will not be executed. It will be executed only when the function is called.

hello()  # Function call output hello this is python

2. Return value

Since there is little difference between whether there is a return value or not, I only describe the function with a return value here.
If a return value occurs in a function, it indicates that the function has a return value.
If you don't know about return, you can take a look at the "keyword of function" at the back of the article.

def return10():
    return 10

a = return10()  # call
print(a)  # 10

After the contemporary code size becomes longer, it will be more troublesome to understand the variable type returned by a function, so you can "write" the type after the function name

# The return value is null
def fun() -> None:

Parametric function

When learning parametric functions, first understand the effective global and local variables.

1. Global and local variables

Global variables refer to variables defined in the global, that is, variables defined outside all functions. They are global and valid at any position.
A local variable is a variable defined internally in a function or loop body. It is only valid internally, and it is invalid beyond the defined range. (local variables can also be local variables in a local, that is, nested functions in functions can also have local variables)
Therefore, variables outside the function cannot be modified directly inside the function

x = 100

def fun():
    x = 200

print(x)  # 100
fun()  # 200
print(x)  # 100

But sometimes I just want to modify it. What should I do?
We can use the global keyword to raise local variables to global variables.

x = 100

def fun():
    global x
    x = 200

print(x)  # 100
fun()  # 200
print(x)  # 200

At this time, the variable can be modified. Similarly, you can use nonlocal to convert external variables into local variables. The use of nonlocal is relatively small, so it is not written in detail here. Interested students can try it.
Note: nonlocal is written in front of the internal variable and can only rise one level.

2. Parameters of function

First, understand what a parameter is. A parameter is a special variable. It is in the parentheses in the function definition. The variable defined in the function will co-exist with the function, that is, the variable only exists in the currently defined function. This sentence is very important to understand the subsequent recursion and other knowledge.

def add(number1, number2):
    return number1 + number2

def print_x(x):

Since it is a parametric function, you must pass in parameters to them when calling them.

num1 = 10
num2 = 11
num3 = add(num1, num2)
print(num3)  # 21
print_x(num3)  # 21

3. Required and default parameters

Required parameters: when calling a function, the parameters that must be passed in are required parameters.
Default parameter: when calling a function, the parameters that can not be passed in are the default parameters. The default parameter will be a default value when it is not passed in.

def add(number1, number2=0):
    return number1 + number2

In this function, number1 is a required parameter, which must be passed in, and number2 is the default parameter, which can not be passed in.
The parameters are also defined in order:

No parameter = mandatory parameter (defined) = default parameter (defined)

Otherwise, an error will be reported during operation.

4. Variable length parameters

Sometimes we want to pass in some parameters, and we don't know their number. It's difficult to define the function with the above method, so we introduce indefinite length parameters. Note that there can only be one variable length parameter of the same type at most, and the variable length parameter is not a required parameter.

4.1 tuple indefinite length

Tuples of variable length can pass no value or a series of values, represented by a *.

def fun(*args):

fun()  # No value transfer
fun('asv', 'a', 87, 2, 4, 3, 4, {"af": "asdf"}, ('bv', 'a'), {4, 62, 74, 1})  # Store incoming data as tuples

4.2 dictionary variable length

The indefinite length of the dictionary has restrictions on the incoming form: it must be passed in the form of key = value. Of course, you can also not transfer values. The function automatically quotes the key into a string.

def fun(**kwargs):

fun()  # No value transfer
fun(name='Ice', age=0)  # {'name': 'Ice', 'age': 0}

4.3 parameter sequence

At this point, we will update the parameter order:
No parameter = "required parameter (defined) =" default parameter (defined) = "tuple indefinite length (* args) =" dictionary indefinite length (* * kwargs)

4.4 input parameters in the form of unpacking

def fun(*args, **kwargs):

tu = (2, 5, 3, 4, 6)
dic = {"name": "Ice", "age": 0}
fun(*tu, **dic)  # *Indicates tuple unpacking, * * indicates dictionary unpacking


When the outer function returns the function body of the inner function, it is called closure.

def fun():
    x = 5

    def fun1():
        nonlocal x
        x -= 1

    def fun2():
        nonlocal x
        x += 1

    return fun1
    # return fun1,fun2 can also return multiple function bodies. The results are stored in tuples. Calling the corresponding function body can be called by unpacking tuples

print(fun())  # <function fun.<locals>.fun1 at 0x000001BA70979EE8>
fun()()  # Execute the function under the closure

If you can't unpack the solution group, you can see this article python learning - tuples

Keyword of function

The return value function mentioned earlier is return. Here is an introduction to return.
Return is used to terminate the function and return the value.
If a function is executed to return, all statements after it will not be executed and the function call will be ended directly.

def fun():

fun()  # 1

3 will not be output here.
If return is followed by a variable or value, the value will be returned at the end of the function. The value can be received with a variable!

def fun():
    return 10

a = fun()  # 1
print(a)  # 10


When a function calls itself, it is called recursion.
For example, the factorial function can be implemented recursively:

def fun(n):
    if n == 1:
        return 1
        return n * fun(n - 1)

print(fun(3))  # 6

When implementing with recursion, pay attention to setting the exit of recursion. In the above recursive function for factorial, the exit is when n is equal to 1.

Anonymous function

As the name suggests, an anonymous function is a function without a name. It is defined by lambda and returned automatically by default, so it can be received by variables.

a = lambda x: x + 1
print(a(5))  # 6

Of course, anonymous functions can also be real names.

def a(x):
    return x + 1

print(a(5))  # 6


Interested students can write this problem to consolidate their function knowledge.

  1. Define a function isPrime(), which can input an integer to judge whether the integer is a prime number. If yes, it returns True and if not, it returns False. (a prime number is also called a prime number. A natural number greater than 1 is called a prime number that cannot be divided by other natural numbers except 1 and itself.)
  2. Define a function to input a string. If the string is arranged in ascending order, it returns UP, if it is arranged in descending order, it returns DOWN, and if it is out of order, it returns False. (the string is passed in in lowercase letters)

The next article will give the answer for your reference.


The homework element is introduced this time. What do you think?
Please give me a compliment. It's very important to me.

ps: now pay attention to me, and you will be an old fan in the future!!!

Next Trailer

Because there are many functions, I will publish them in two articles. The next article will list some built-in functions.

Tags: Python

Posted on Tue, 23 Nov 2021 09:09:33 -0500 by Xyn1407