Hello Python -- Python 3 function

Posted by AbiusX on Fri, 25 Feb 2022 17:11:26 +0100

1, Function definition

1. Function definition

Python defines functions using the def keyword. The general format is as follows:

def function_name(parameter_list):

By default, parameter values and parameter names match in the order defined in the function declaration.

The function code block begins with the "def" keyword, followed by the function identifier name and parentheses ().

Parentheses can be used to define any argument between parentheses and arguments.

The first line of the function can optionally use a document string to describe the function description.

The function content starts with a colon and is indented.

Examples of function definitions are as follows:

def add(x, y):
    result = x + y
    return result

2. Return value of function

The function ends the function with "return" and returns one or more values to the caller. A return without an expression is equivalent to returning None.

def get_fruits():
    apple = "Apple"
    banana = "Banana"
    orange = "Orange"
    return apple, banana, orange

a,b,c = get_fruits()
print(a, b, c)

2, Function call

1. Function call

The function definition only gives the function a name and specifies the parameters and code block structure contained in the function.

The function call directly uses the defined function name and passes the corresponding parameters.

2. Recursive restrictions on function calls

Python sets the maximum number of recursive calls of functions by default, which can be set directly by developers. The setting method is as follows:


import sys

sys.setrecursionlimit(100) # Set the maximum number of recursions to 100

3, Function parameters

1. Required parameters

Required parameters are parameters that must be passed when a function is called.


def add(x, y):
    result = x + y
    return result

add(3, 2)

2. Keyword parameters

When the keyword parameter is used for function call, the formal parameter keyword is used to assign the actual parameter to the corresponding formal parameter of the function. In the process of function call, the order of the actual parameter passed may not match the order of the formal parameter, but all the necessary parameters must be assigned.


def add(x, y):
    result = x + y
    return result

add(y=2, x=3)

In the above code, the actual parameters passed by the call of the add function actually specify the corresponding formal parameters by specifying the keyword parameters. It is not necessary to match the formal parameters in order, but all the parameters must be passed.

3. Default parameters

During the definition of a function, you can specify the default value for the parameter, and the parameter must be placed to the left of the default parameter.


def print_student(name, gender="male", age=28):

print_student("Bauer", "male", 30)

print_student(age=30, name="Bob")

When calling a function, you can use keyword parameters to assign values to formal parameters. The default parameters can be defaulted, but the mandatory parameters must be assigned, and the mandatory parameters can be assigned with keyword parameters. If the mandatory parameters do not use keyword parameters, the mandatory parameters must be passed in strict accordance with the order defined by the function. The default parameters can be selectively assigned with keyword parameters, and the default parameters that are not passed with keyword parameters will use the default value.

4. Variable parameter

Variable parameters define variable parameters by using * modifier formal parameters.

When defining a function, you can define variable parameters and pass multiple variable actual parameters when calling a function.


def add(*args):
    result = 0;
    for x in args:
        result += x
    return result

c = add(1, 2, 3, 4)
c = add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tup1 = 1, 2, 3, 4
c = add(*tup1) # Incoming sequence
list1 = [1, 2, 3]
c = add(*list1)

Corresponding to the function with variable parameters defined, if you need to pass in the sequence as the actual parameter, you need to add * before the sequence.

If there are variable parameters and default parameters during function definition, keyword parameters can be used to specify default parameters during function call.


def add(x, *args, y=100):
    result = x + y;
    for i in args:
        result += i
    return result

c = add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # 155
c = add(1, 2, 3, 4, 5, 6, 7, 8, 9, y=10) # 55

In Python, if the variable parameter is placed to the left of the default parameter when the function is defined, the default parameter needs to be explicitly specified with keyword parameters.

5. Keyword variable parameter

Keyword variable parameters are defined by using * * modification form parameters. Keyword variable parameters are dictionary types, and keyword variable parameters are optional parameters.


def average_score(**args):
    result = 0;
    for key, value in args.items():
        result += value
        print(key + ": ", value)
    result = result / len(args)
    print("Average score is ", result)
    return result

book = {"Bauer": 90, "Bob": 100, "Lisa": 70, "Lee": 100}
average_score(Bauer=100, Lisa=70, Lee=100)

During function call, keyword variable parameters can pass multiple key value pairs, and pages can directly pass dictionary type variables. At this time, * * needs to be used to modify dictionary variables.

4, Anonymous function

python uses lambda expressions to create anonymous functions, which are defined as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The function body of the anonymous function defined by lambda expression is not a code block, so only limited logic can be encapsulated in lambda expression.

Lambda expressions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.

Although lambda function can only write one line, it is not equivalent to C or C + + inline function. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.

# -*- coding:utf-8 -*-

sum = lambda arg1, arg2: arg1 + arg2;

# Call sum function
print(sum(10, 20))
print(sum(20, 20))

5, Variable scope

All variables of the program can not be accessed anywhere. The access authority depends on where the variables are assigned. The scope of the variable determines which part of the program can access which specific variable name.

Variables defined inside the function have local scope, while those defined outside the function have global scope. Local variables inside the code block will overwrite global variables. When modifying the value of global variables within the local scope, you need to use the global keyword to declare the corresponding global variables, indicating that global variables are used within this scope.

Local variables can only be accessed inside the declared function, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope.

# -*- coding:utf-8 -*-

base = 100

def sum(*args):
    global base
    base = 0
    result = 0;
    for i in args:
        result += i
    return result + base;

c = sum(1,2,3,4,5,6,7,8,9,10)
print(c) # 55
print(base) # 0

Topics: Python function