[Python] Advanced Functions

Advanced Functions

Role of function arguments and return values

  • When you define a function, whether to accept parameters, or return results is based on the actual functional requirements to decide!
  1. If the function data uncertain internal processing , the data may be passed to the outside in the internal parameter function
  2. If you want a function execution is completed, report the results to the outside world , you can increase the return value of the function

Advanced function's return value

  • return In fact, one can only return a data, if you want to achieve a return more data, you can use the "container" loaded up => such as the Python tuple, Java arrays

A plurality of return value of the function

def measure():
    """
    测量温度和湿度
    :return: 同时返回温度和湿度
    """
    print("测量开始...")
    temp = 39
    wetness = 50
    print("测量结束...")
    # 元组-可以包含多个数据,因此可以使用元组让函数一次返回多个值
    # 如果函数返回的类型是元组,小括号可以省略
    # return (temp,wetness)
    return temp,wetness

# result接受的是一个元组
result = measure()
print(result)

# 如果函数返回的类型是元组,同时希望单独的处理元组中的元素
# 可以使用多个变量,一次接受函数的返回结果
gl_temp,gl_wetness = measure()

print(gl_temp)
print(gl_wetness)

Interview questions - two digital exchange

Questions asked

  1. There are two integer variables,a=6,b=100
  2. Do not use other variables, the exchange value of the two variables
a = 6
b = 100

# 解法1: 使用中间变量
temp = a
a = b
b = temp

# 解法2 : ^的运算性质,
a = a ^ b
b = a ^ b
a = a ^ b

# 解法3: Python专用
# 提示: 等号的右边是一个元组,只是把小括号省略
a, b = b, a

Advanced function parameters

For the assignment of function parameters

  • Inside the function, the parameters for the use of an assignment statement , is to pass the time without affecting the calling function argument variables
    • Whether parameter is passed variable or immutable , as long as the parameters for the use of an assignment statement , will only modify refers to a local variable inside a function, it does not affect the external variable references

Bottom line: For the assignment function parameters will not affect the outside world, but to create a new local variable with the same name

def demo(num,num_list):
    print("函数内部的代码")
    # 在函数内部,针对函数参数使用赋值语句,不会修改到外部的实参变量
    num = 100
    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)

To change the function of the type of the variable parameters by the method

  • If the parameter passed is the variable type , the internal functions, using the method to modify the content data, it will also affect the external data

For the function parameters, the assignment can not be changed externally, but may affect the type of external variable by means of

def demo(num_list):
    print("函数内代码")
    # 使用方法修改列表的内容
    num_list.append(9)
    print(num_list)
    print("函数执行完成")

gl_list = [1,2,3]
demo(gl_list)
print(gl_list)

Interview questions - +=

  • In Python, a list of variables that call +=is a list of variables in the implementation of the essence extendmethod does not modify the variable reference => normal is to change the reference to a variable, but + = equivalent of the list extend(), does not change the reference list
In [1]: a = 1
In [2]: var1 = id(a)
In [3]: a += 1
In [4]: var2 = id(a)
In [5]: var1 == var2
Out[5]: False
# 上下两者是不一样的
# 前者是相加再重新赋值,后者是调用list.extend()
num_list = num_list + num_list
num += num_list
def demo(num, num_list):
    print("函数开始")
    # num += num => num = num + num
    num += num

    # 列表使用 += 不会做相加再赋值的操作!
    # num_list += num_list => num_list.extend()
    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)

The default parameters

  • When you define a function, you can give a parameter to specify a default value , with a default value of the parameter named default parameter => default value is determined to advance arguments
  • When you call the function, if no incoming default parameters specified value, use the custom function inside the function parameter default values
  • The default function parameters, the common value set to the default value of the parameter , thereby simplifying the calling function

the list.sort () defaults

gl_list = [6,3,9]

# 默认就是升序排序,因为这种应用需求
gl_list.sort()
print(gl_list)

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

The default parameter specifies the function

  • Use an assignment statement after the argument, you can specify default values ​​for parameters
# 假设班上的男生较多,所以这里使用男生作为缺省值
def print_info(name,gender=True):
    """
    :param name: 班上同学的名字
    :param gender: True 男生 False女生
    """
    gender_text = "男生"
    if not gender:
        gender_text = "女生"
    print("%s 是 %s" % (name,gender_text))

print_info("小明")
print_info("小美",gender=False)

prompt

  1. The default parameters, need to use the most common value as the default value! => For examplegender=True
  2. If a value of the parameter can not be determined , it should not set the default values, specific values of the function call, passing from the outside! => Such as namesubstantially not the same for each, it should not set the default value

Notes default parameters

  1. Define the location of default parameters
    • Must ensure that the default parameters with default at the end of the parameter list
    • So, the following definitions are wrong!
    # 下面缺省函数参数的位置是错误的
    def print_info(name,gender=True,title)
  2. Call the function with multiple default parameters
    • In the function call , if there is more than one default parameters, you need to specify the parameter name , so the interpreter to be able to know the relationship between 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("小美",gender=False)
print_info("老王",title="班长")

Multi-value parameter (know)

Support for multi-parameter definition of function

  • Sometimes may need a function parameter can handle the number of uncertain time, this time, you can use the multi-value parameter
  • PythonThere are two kinds of multi-value parameter:
    • Increase the parameter name in front of a* acceptable tuple
    • Increase the parameter name in front of two* can accept dictionary
  • Generally when a multi-value parameter named, accustomed to using the following two names
    • *args- storing tuples parameter, a front*
    • **kwargs- Keep dictionary parameters, there are two front*
    • argsIs argumentsan abbreviation, meaning there are variables, kwis keywordan abbreviation, kwargsyou can remember the key parameters

Multi-value parameter

def demo(num, *args, **kwargs):
    print(num)
    print(args)
    print(kwargs)

#   num (         ) {                              }
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 be able to read Daniel code

Multi-parameter case - a plurality of digital computing and any

demand

  1. Definition of a function sum_numberscan accept any number of integers
  2. Functional requirements: the transfer of all the digital accumulation and returns the accumulated result
def sum_numbers(*args):
    # 打印args这个元组
    print(args)
    return sum(args)

result = sum_numbers(1,2,3,4,5)
print(result)

Tuples and dictionaries unpacking

  • When calling functions with multi-value parameter, if you want:
    • A tuple variable passed directly toargs
    • A dictionary variable is passed directly to thekwargs
  • It can be used unpacking , simplified transmission parameters, unpacking manner when:
    • In the former group of variables yuan , an increase of a*
    • In the dictionary of variables , increased two*
      `` `Python
      DEF Demo (* args, ** kwargs):
      Print (args)
      Print (kwargs)

Tuple variables / variable dictionary

gl_tuple=(1,2,3)
gl_dict = {"name":"小明","age":18}

Unpacking syntax simplified transfer tuple variable / variables dictionaries

demo(*gl_tuple,**gl_dict)

```

Recursive function

Features recursive function

Guess you like

Origin www.cnblogs.com/Rowry/p/11832445.html