[100 days proficient in python] Day10: function creation and call, parameter passing, return value, variable scope and anonymous function

Table of contents

1. Function creation and calling 

1.1 Creation of functions

1.2 Call function 

2 parameter passing

2.1 Delivery method

2.2 Formal parameters and actual parameters

2.3 Positional parameters

2.4 Keyword arguments

2.5 Variable parameters

2.6 Setting default values ​​for parameters

3 return value

4 Scope of variables

4.1 Local variables

4.2 Nested variables

4.3 Global variables

5 Anonymous function (Lambda function)

         A Python function is a set of reusable blocks of code that perform a specific task. Functions can receive input parameters and return a result.

1. Function creation and calling 

1.1 Creation of functions

        In Python, the syntax for creating a function uses defa keyword followed by the name of the function, its argument list, and a colon (:). Code blocks for functions must be indented, usually four spaces. Functions can have a documentation string (docstring) that describes the purpose and functionality of the function.

The following is an example of the syntax for creating a function:

def function_name(parameter1, parameter2, ...):
    """文档字符串(可选)"""
    # 函数代码块
    # ...
    # 可以使用 return 语句返回结果(可选)
    # return result

  • function_nameIs the name of the function, following the Python naming rules, usually in lowercase letters, with underscores separating words.
  • parameter1, parameter2, ...is the parameter list of the function to receive the input data. There can be multiple parameters, separated by commas. Parameters can be required parameters, default parameters, variable parameters and keyword parameters, which can be selected according to needs.
  • 文档字符串is optional and describes the purpose and functionality of the function. It is located on the first line of the function definition and can be help()viewed through the function.
  • The function code block is the main body of the function, which contains the execution logic of the function. Code blocks must be indented, and use the same indentation level inside functions.

Functions can use returnstatements to return a result, or they can have no return value. When the function reaches returna statement, it stops executing and returns the result to the caller. If the function has no explicit returnstatement, it will return by default None.

Here is an example of a simple function:

def add(a, b):
    """这个函数用于将两个数字相加并返回结果"""
    return a + b

# 调用函数并打印结果
result = add(5, 3)
print(result)  # 输出:8

1.2 Call function 

        Calling a function refers to using a function in your code to perform a specific action. The syntax for calling a function is to put parentheses after the function name, and pass parameters to the function (if the function defines parameters).

Following is the basic syntax for calling a function:

result = function_name(argument1, argument2, ...)

  • function_nameis the name of the function to call.
  • argument1, argument2, ...is the parameter value to pass to the function.

When calling a function, the passed parameter values ​​must match the order of the parameters in the function definition. If the function has multiple parameters, the parameter values ​​can be passed in sequence. If the function has default parameters, you can choose not to pass them and the function will use the default values.

Here is an example of a simple function call:

def add_numbers(a, b):
    return a + b

result = add_numbers(10, 20)
print(result)  # 输出结果为 30

In this example, we define a add_numbersfunction called that takes two arguments aand badds them together and returns the result. Then we call this function and pass the parameter values 10​​and 20get the result 30and print it. 

2 parameter passing

2.1 Delivery method

      In Python, parameter passing can be realized in two ways: passing by value and passing by reference. It depends on whether you are passing an immutable or mutable object.

Pass by Value:

        When passing immutable objects (such as integers, strings, tuples, etc.), Python uses value passing. In passing by value, the function receives a copy of the actual parameter, and the modification of the formal parameter will not affect the actual parameter.

def modify_number(x):
    x = x + 1

number = 5
modify_number(number)
print(number)  # 输出 5,函数中对形参 x 的修改不影响原始变量 number

Pass by Reference:

        When passing mutable objects (such as lists, dictionaries, etc.), Python uses reference passing. In passing by reference, the function receives the reference of the actual parameter object, and the modification of the formal parameter will affect the actual parameter.

def modify_list(my_list):
    my_list.append(4)

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # 输出 [1, 2, 3, 4],函数中对形参 my_list 的修改影响原始列表对象

        It should be noted that in passing by reference, if the formal parameter is directly assigned inside the function, the reference to the original object will be broken, so that the original object will not be affected.

def modify_list(my_list):
    my_list = [7, 8, 9]  # 在函数内部对形参进行赋值,断开与原始对象的引用
    print(my_list)

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # 输出 [1, 2, 3],函数内部的赋值不影响原始列表对象

Summary: The way parameters are passed in Python depends on whether the passed object is mutable. For immutable objects, pass by value; for mutable objects, pass by reference.

2.2 Formal parameters and actual parameters

Formal Parameters:

        Formal parameters are the parameter names defined in parentheses after the function name when the function is defined. Formal parameters act as local variables in the function body, and they are placeholders for the function to receive the value passed from the outside.

In the following example, xand yare the formal parameters:

def add_numbers(x, y):
    sum = x + y
    return sum

 Actual Parameters:

        Actual parameters are concrete values ​​passed to a function when the function is called. They are actual data or objects used to fill formal parameters in function definitions. In the following example, 3and 5are the actual parameters:

result = add_numbers(3, 5)

 When we call a function, we pass actual parameters to the function, and the values ​​of these actual parameters will be copied to the corresponding formal parameters, and then used in the function body. After the function call ends, the scope of the function's local variables (that is, formal parameters) also ends, and their values ​​will not affect variables outside the function.

It should be noted that when the function is called, the number and type of the actual parameters must match the number and type of the formal parameters in the function definition, otherwise an error will result.

2.3 Positional parameters

        Positional arguments (Positional Arguments): Positional arguments are the most common way of passing function parameters. They receive the actual parameters passed in order in the order in which the function is defined. When calling a function, the position of the actual parameter corresponds to the position of the formal parameter. 

def add_numbers(a, b):
    return a + b

result = add_numbers(3, 5)
print(result)  # 输出 8

2.4 Keyword arguments

        Keyword Arguments (Keyword Arguments): Keyword arguments refer to passing parameters by specifying the parameter name when the function is called, so that they do not have to be passed in order of position. Keyword arguments can make function calls clearer and more readable. 

def print_info(name, age):
    print("Name:", name)
    print("Age:", age)

print_info(name="Alice", age=30)

2.5 Variable parameters

        A variadic parameter is a special type of parameter that can receive a variable number of parameters. In Python, there are two types of variadic parameters:

  • *args: Used to receive any number of positional parameters, representing a tuple.
  • **kwargs: Used to receive any number of keyword arguments, representing a dictionary (dict).
def add_all_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

result = add_all_numbers(1, 2, 3, 4, 5)
print(result)  # 输出 15

def print_person_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_person_info(name="Alice", age=30, city="New York")

 Note: When defining a function, the order of positional parameters, variable parameters, and keyword parameters should be: positional parameters -> *args -> **kwargs. For example:

def my_function(a, b, *args, **kwargs):
    # 函数体

The above parameter definitions are legal and are the recommended order.

2.6 Setting default values ​​for parameters

        In Python, you can set default values ​​for function parameters, so that when the function is called, if the value of the parameter is not passed, the default value will be used.

        The syntax for setting a default value is to use the equal sign (=) in the function definition to specify a default value for the parameter.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

# 调用函数时未指定greeting参数,将使用默认值
greet("Alice")  # 输出:Hello, Alice!

# 也可以在调用函数时指定greeting参数的值
greet("Bob", "Hi")  # 输出:Hi, Bob!

 Precautions:

  1. The default value parameter should be placed after the positional parameter, otherwise an error will be reported.
  2. The default value is only bound once when the function is defined, that is, each time the function is called, if the corresponding parameter is not passed, the previously bound default value will be used.

If you want the default value parameter to be a new object every time the function is called, you can use it Noneas the default value and handle it as needed in the function body.

def add_to_list(value, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(value)
    return my_list

# 第一次调用函数
result1 = add_to_list(1)
print(result1)  # 输出:[1]

# 第二次调用函数,不会影响之前的结果
result2 = add_to_list(2)
print(result2)  # 输出:[2]

3 return value

        In Python, functions can returnreturn a value to the caller via a statement. The return value is the data that will be passed to the caller after the function finishes executing. The return value can be of any data type, including integers, floating point numbers, strings, lists, dictionaries, etc.

        The function can have no return value, and the function will return by default after execution None. returnIf there are no statements in the function , or returnno expression following it, the function returns None.

Here is an example function that takes two arguments and returns their sum:

def add_numbers(a, b):
    sum = a + b
    return sum

result = add_numbers(3, 5)
print(result)  # 输出结果为 8,函数返回了参数3和5的和

4 Scope of variables

        In Python, the scope of a variable refers to the range in which the variable can be accessed in the program. There are three types of scopes in Python:

4.1 Local variables

        When a variable is defined inside a function, its scope is the local scope of the function and can only be accessed inside the function.

def my_function():
    x = 10  # 局部变量
    print(x)

my_function()  # 输出:10
print(x)  # 报错,x在函数外部不可访问

4.2 Nested variables

        Nested scope refers to the situation where another function is defined inside a function. Inner functions can access variables defined in outer functions.

def outer_function():
    y = 20  # 嵌套作用域变量
    def inner_function():
        print(y)
    inner_function()

outer_function()  # 输出:20

4.3 Global variables

        When a variable is defined outside a function, its scope is the global scope and can be accessed throughout the program.

global_variable = 30  # 全局变量

def my_function():
    print(global_variable)  # 可以在函数内部访问全局变量

my_function()  # 输出:30
print(global_variable)  # 输出:30

 other:

 Inside a function, globalkeywords can be used to declare a variable as a global variable, so that modifications to the variable inside the function will also affect the global scope. as follows:

x = 50  # 全局变量

def update_global():
    global x
    x = x + 1

update_global()
print(x)  # 输出:51

 Note: Inside the function, if you use =to assign a value to a variable, the variable will be regarded as a local variable by default. If you want to modify a global variable, you must use globalkeywords to declare it. Otherwise, a new local variable is created inside the function without affecting the global variable.

5 Anonymous function (Lambda function)

        In Python, anonymous functions, also known as Lambda functions, are a special type of function that allow you to create simple, one-line functions, often used to define simple functionality without the need to name them.

The syntax of a Lambda function is as follows:

lambda arguments: expression

Among them, argumentsis the parameter list, which can be any number of parameters, but there can only be one expression. The execution result of the Lambda function is the result of this expression.

Here is an example of a simple Lambda function:

add = lambda x, y: x + y
result = add(3, 5)
print(result)  # 输出:8

 In this example, we define a Lambda function addthat takes two parameters xand yreturns their sum.

Lambda functions are often used when you need a simple function, but don't want to define a complete function. For example, when sorting a list, you can use a Lambda function to specify the sorting key:

fruits = ['apple', 'orange', 'banana', 'cherry']
fruits.sort(key=lambda x: len(x))
print(fruits)  # 输出:['apple', 'cherry', 'orange', 'banana']

In this example, we use the Lambda function as the parameter sort()of the method key, which is used to specify the length of the string as the key for sorting. This way fruitsthe list will be sorted by string length from shortest to longest.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131872032