Functions of Python basic knowledge (1)

Function (must be defined before use)

A function is to integrate and name a piece of code blocks with independent functions, and call this name at the required position to complete the corresponding requirement. Code reuse can be achieved more efficiently.

(1) Define function (parameters can be empty)

def  函数名(参数) :
代码1
代码2
代码3

(2) Call function (parameters can be empty)

函数名(参数) 

(3) Matters needing attention

In the process of using the function, when the function is called, it will return to the function definition and execute it again.

(4) Function return value

The function returns a value for receiving, using return data to operate.

  • return is used to exit the function, and the operations below return will not be executed.

  • return data1, data2, data3 # If multiple data is returned, and the data type is not defined, it will be a tuple after receiving (return multiple values)

  • return {"":"","":""} Return a dictionary type data

  • return [data one, data two, data three] return a list of data

(5) The documentation of the function

Definition: (Only in the first line of the writing code of the function to write the description document) When there are parameters, you can use the carriage return to describe the parameters

def  函数名 :
""" 说明文档位置  """
代码
........

View: Use the help (function name) function to view the documentation of the function

2. Variable scope

1. Local variables (the effective range is within a certain function body)

Function: In the function body, the data is temporarily saved, that is, when the function is called, the variable is destroyed.

2. Global variables (variables that can take effect both in the body and outside of the function)

  • Defined outside the function, so the function can be used.

  • If you want to modify a global variable in a function, you need to declare it with the global global variable name before the function modifies that global variable statement

a=100
def printaelse():
    global a
    a=200
    print(a)

3. Function parameters

The parameters of the function do not need to define the type of the parameter, but directly use the defined variables for transmission. The functions received are called formal parameters, and the data passed in are called actual parameters.

1. Positional parameters (the order and number of parameters passed and defined must be the same)

E.g:

  • Definition: add_num (a, b)
  • Use: add_num ("Tom", 22)

2. Keyword parameters (the order of function parameters is cleared)

Function calls are specified in the form of "key=value".

Note: If there are positional parameters, the keyword parameters must be after the positional parameters, but the order of the keyword parameters is not required.
E.g:

  • Definition: add_num (a, b)
  • Use: add_num ("Tom", b = 22)

3. Default parameters

It is used to define a function and provide a default value for the parameter. The value of the default parameter may not be passed when the function is called.

Note: If there is a default parameter, the default parameter must be after the positional parameter. If it is a default parameter, modify the default parameter value, otherwise use the default parameter value.
E.g:

  • Definition: add_num (a, b = 20)
  • Use: add_num ("Tom") or add_num ("Tom", 18)

4. Variable length parameters

Used when you are not sure how many parameters will be passed in the call (no parameters can be passed), you can use packing positional parameters, or use packing keyword parameters to pass parameters

(1) Position parameters of variable length parameters

E.g:

  • Definition: add_num (* arg)
  • Use: add_num ("Tom") or add_num ("Tom", 18)

Note: arg receives all the parameters passed in the function call and is a tuple type.

(2) Keyword parameters of variable length parameters

E.g:

  • Definition: add_num (* * arg)
  • Use: add_num (name= “Tom”) or add_num (name= “Tom”, age=18)

Note : arg receives all the parameters passed in the function call and is a dictionary type.

4. Unpacking

1. Unpacking tuples

If you use return to return multiple values, a tuple type will be returned by default. Or the parameter received by the position parameter of the variable length parameter is also a tuple. What about unpacking tuples:
define the function:

def return_data():
return 100,200     

When receiving: (receive a few data with a few data, then you can unpack the tuple into separate data)

a , b = return_data()   # a为100,b为200

2. Dictionary unpacking (the key value in the dictionary is taken out)

dict1 = {
    
     "name" : "Tom" , "age" : 18 }   
a,b=dict1  # 此时 a=name,b=age
dcit1[a]  # 数据为Tom     
dict2[b]  # 数据为18

3. Exchange variables (easy way without the help of the third variable)

a , b = 1 , 2     a , b = b , a

5. Reference (in Python, the value is passed by reference)

We can use id() to judge whether two variables are references to the same value, which can be understood as the address identification of the address

1. Variable type and immutable type:

Variable type:

List dictionary collection

When the data is modified, the original data is modified.

Immutable type:

Integer floating-point string tuple

When data is modified, it is not the original data that is modified, but a new data.

2. Use quotes as actual parameters to pass values:

If the value is passed, the immutable type is used as an actual parameter to pass the value. When the formal parameter changes, the actual parameter will not change accordingly. In this case, it is equivalent to a unilateral value transfer.

Advanced functions

aims

  • The role of function parameters and return values
  • Advanced function return value
  • Advanced function parameters
  • recursive function

01. The role of function parameters and return values

Functions can be combined with each other according to whether they have parameters and whether they have return values. There are 4 combinations in total

  • No parameters, no return value
  • No parameters, return value
  • There are parameters, no return value
  • Has parameters, return value
    Insert picture description here
    defining a function, whether the received parameters, return results or whether, based on the actual functional requirements to decide!

1. If the data processed inside the function is uncertain, you can pass external data to the function as parameters

2. If you want to report the execution result to the outside world after a function is executed, you can increase the return value of the function

1.1 No parameters, no return value

This type of function does not receive parameters and has no return value. The application scenarios are as follows:

  • Just simply do one thing, such as display a menu
  • Operate on global variables within the function, for example: create a new business card, and record the final result in the global variable

note:

  • If the data type of the global variable is a variable type, you can use the method to modify the content of the global variable inside the function- the reference of the variable will not change

  • Inside the function, the variable reference will be modified only when the assignment statement is used

1.2 No parameters, return value

This type of function does not receive parameters, but has a return value. The application scenarios are as follows:

  • Collect data, such as a thermometer, and the return result is the current temperature without passing any parameters

1.3 There are parameters, no return value

This type of function receives parameters and has no return value. The application scenarios are as follows:

  • The code inside the function remains unchanged, processing different data for different parameters
  • For example, the business card management system modifies and deletes the business cards found

1.4 There are parameters and return values

This type of function receives parameters and has a return value at the same time. The application scenarios are as follows:

  • The code inside the function remains unchanged, handles different data for different parameters, and returns the expected processing result
  • For example, the business card management system uses dictionary default values ​​and prompt messages to prompt the user to input content.
    If input, return the input content.
    If there is no input, return the dictionary default value.

02. Advanced function return value

  • In program development, sometimes, it is hoped that after a function is executed, the caller will be told a result, so that the caller can do follow-up processing for the specific result
  • The return value is the final result given to the caller after the function has completed its work
  • Use the return keyword in the function to return the result

Question: Can a function return multiple results after execution?
Example-temperature and humidity measurement
Suppose you want to develop a function that can return the current temperature and humidity at the same time.
First, complete the function of returning the temperature as follows:

def measure():
   """返回当前的温度"""
   
   print("开始测量...")
   temp = 39
   print("测量结束...")
   
   return temp
​
result = measure()
print(result)

In the use of the tuple at the same time the return temperature, the humidity can be returned

The transformation is as follows:

def measure():
   """返回当前的温度"""print("开始测量...")
   temp = 39
   wetness = 10
   print("测量结束...")return (temp, wetness)

Tip: If a function returns a tuple, the parentheses can be omitted

skill

In Python, you can assign a tuple to multiple variables at the same time using assignment statements

Note: The number of variables needs to be consistent with the number of elements in the tuple

result = temp, wetness = measure()

Interview question-exchange two numbers. The
question requires
two integer variables a = 6, b = 100.
No other variables are used, and the values ​​of the two variables are exchanged.
Solution 1-Use other variables

c = b
b = a
a = c

Solution 2-Don't use temporary variables

a = a + b
b = a - b
a = a - b

Solution 3-Python specific, using tuples

a, b = b, a

03. Advanced function parameters

3.1. Immutable and variable parameters

Question 1 : In a function, using assignment statements for parameters will affect the actual parameter variables passed when the function is called? ——No!

  • Regardless of whether the passed parameter is mutable or immutable
  • As long as the assignment statement is used for the parameter, the reference of the local variable will be modified within the function, and the reference of the external variable will not be affected
def demo(num, num_list):print("函数内部")# 赋值语句
   num = 200
   num_list = [1, 2, 3]print(num)
   print(num_list)print("函数代码完成")
​
​
gl_num = 99
gl_list = [4, 5, 6]
demo(gl_num, gl_list)
print(gl_num)
print(gl_list)

Question 2 : If the passed parameter is a variable type, inside the function, using the method to modify the content of the data will also affect the external data

def mutable(num_list):# num_list = [1, 2, 3]
   num_list.extend([1, 2, 3])
   
   print(num_list)
​
gl_list = [6, 7, 8]
mutable(gl_list)
print(gl_list)

Interview questions-+=

In python, the list variable call += essentially executes the extend method of the list variable, and does not modify the variable reference

def demo(num, num_list):print("函数内部代码")# num = num + num
   num += num
   # num_list.extend(num_list) 由于是调用方法,所以不会修改变量的引用
   # 函数执行结束后,外部数据同样会发生变化
   num_list += num_list
​
   print(num)
   print(num_list)
   print("函数代码完成")
​
​
gl_num = 9
gl_list = [1, 2, 3]
demo(gl_num, gl_list)
print(gl_num)
print(gl_list)
print(num)

3.2 Default parameters

  • When defining a function, you can assign a default value to a parameter. A parameter with a default value is called a default parameter
  • When the function is called, if the value of the default parameter is not passed in, the default value of the parameter specified when the function is defined is used inside the function
  • The default parameter of the function, set the common value as the default value of the parameter, thereby simplifying the call of the function.
    For example: the method of sorting the list
gl_num_list = [6, 3, 9]# 默认就是升序排序,因为这种应用需求更多
gl_num_list.sort()
print(gl_num_list)

# 只有当需要降序排序时,才需要传递 `reverse` 参数
gl_num_list.sort(reverse=True)
print(gl_num_list)

Specify the default parameters of the function

  • Use the assignment statement after the parameter to specify the default value of the parameter
def print_info(name, gender=True):
​
   gender_text = "男生"
   if not gender:
       gender_text = "女生"print("%s 是 %s" % (name, gender_text))

prompt

1. The default parameter, you need to use the most common value as the default value!

2. If the value of a parameter cannot be determined, the default value should not be set. The specific value is passed by the outside world when the function is called!

Note on default parameters

1) Definition location of default parameters

  • It must be ensured that the default parameters with default values ​​are at the end of the parameter list
  • Therefore, the following definition is wrong!
def print_info(name, gender=True, title):

2) Call a function with multiple default parameters

  • When calling a function, if there are multiple default parameters, you need to specify the parameter name, so that the interpreter can know the corresponding relationship of the parameters!
def print_info(name, title="", gender=True):
   """
​
  :param title: 职位
  :param name: 班上同学的姓名
  :param gender: True 男生 False 女生
  """
​
   gender_text = "男生"if not gender:
       gender_text = "女生"print("%s%s 是 %s" % (title, name, gender_text))
​
​
# 提示:在指定缺省参数的默认值时,应该使用最常见的值作为默认值!
print_info("小明")
print_info("老王", title="班长")
print_info("小美", gender=False)

3.3 Multi-valued parameters (know)

Define functions that support multi-value parameters

  • Sometimes it may be necessary that the number of parameters that a function can handle is uncertain. At this time, multi-value parameters can be used
  • There are two multi-value parameters in python:
    add one * before the parameter name to receive tuples and
    add two * before the parameter name to receive the dictionary
  • Generally, when naming multi-value parameters, it is customary to use the following two names
    *args —— store tuple parameters, preceded by a *
    **kwargs —— store dictionary parameters, the two preceding *
    args are the abbreviations of arguments and have variables The meaning of
    kw is the abbreviation of keyword, kwargs can memorize key-value pair parameters
def demo(num, *args, **kwargs):print(num)
   print(args)
   print(kwargs)
​
​
demo(1, 2, 3, 4, 5, name="小明", age=18, gender=True)


Tip : multi-parameter applications will often appear in some framework developed by Daniel on the network, known multi-value parameter, help us to understand Daniel code

Multi-value parameter case-calculate the sum of any number of numbers

Requirements
Define a function sum_numbers, any number of integers that can be received.
Function requirement: accumulate all the passed numbers and return the accumulated result

def sum_numbers(*args):
​
   num = 0
   # 遍历 args 元组顺序求和
   for n in args:
       num += n
​
   return num
​
print(sum_numbers(1, 2, 3))

Unpacking of tuples and dictionaries (know)

When calling a function with multi-value parameters, if you want:

  • Pass a tuple variable directly to args
  • Pass a dictionary variable directly to kwargs

You can use unpacking to simplify the transfer of parameters. The way to unpack is:

  • Before the tuple variable, add a *
  • Before the dictionary variable, add two *
def demo(*args, **kwargs):print(args)
   print(kwargs)
# 需要将一个元组变量/字典变量传递给函数对应的参数
gl_nums = (1, 2, 3)
gl_xiaoming = {
    
    "name": "小明", "age": 18}# 会把 num_tuple 和 xiaoming 作为元组传递个 args
# demo(gl_nums, gl_xiaoming)
demo(*gl_nums, **gl_xiaoming)

04. Recursion of functions

The programming technique of function calling itself is called recursion

4.1 Characteristics of recursive functions

Features

  • A function calls itself
  • Other functions can be called inside the function, of course, you can also call yourself inside the function

Code characteristics

  • The code inside the function is the same, but the processing results are different for different parameters
  • When the parameter satisfies a condition, the function is no longer executed.
    This is very important. It is usually called a recursive exit, otherwise an endless loop will occur!

Sample code

def sum_numbers(num):

    print(num)
    
    # 递归的出口很重要,否则会出现死循环
    if num == 1:
        return

    sum_numbers(num - 1)
    
sum_numbers(3)

Insert picture description here

4.2 Recursive Case-Calculating Number Accumulation

demand

Define a function sum_numbers

Able to receive an integer parameter of num

Calculate the result of 1 + 2 +… num

def sum_numbers(num):

    if num == 1:
        return 1
    
    # 假设 sum_numbers 能够完成 num - 1 的累加
    temp = sum_numbers(num - 1)

    # 函数内部的核心算法就是 两个数字的相加
    return num + temp

print(sum_numbers(2))

Insert picture description here

Hint: Recursion is a programming technique, and it will feel a bit difficult to get in touch with it for the first time! It is especially useful when dealing with uncertain loop conditions, such as traversing the entire file directory structure

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113351516
Recommended