Function parameters, return values, recursive function

Advanced Functions

aims

  • Role of function arguments and return values
  • Advanced function's return value
  • Advanced function parameters
  • recursive function

01. role of function arguments and return values

The function has no parameters and there is no return value , can be combined with each other , a total of four kinds of combinations

  1. No parameters and returns no value
  2. No parameters, return values
  3. There are parameters, no return value
  4. There are parameters, return values

Defining a function, whether the received parameters, return results or whether , 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

1.1 no parameters and returns no value

Such a function, no arguments, returns no values, the following scenarios:

  1. Just simply do one thing , for example, to display the menu
  2. Inside the function operates on the global variable , for example: a new card , the end result is recorded in a global variable in

note:

  • If the data type of a global variable is a variable type , the function can be used within a method to modify the contents of the global variable - a reference variable does not change
  • Inside the function, use an assignment statement will reference modifying variables

1.2 no parameters, return value

Such a function, the parameter is not received, but has a return value, the following scenarios:

  • Data collection, for example a thermometer , return the result is the current temperature, without the need to pass any parameters

1.3 There are parameters, no return value

Such a function, reception parameters, no return value, the following scenarios:

  • Internal function code remains the same, for the processing of different data different parameters
  • Such as card management system for card found do modify , delete operations

1.4 There are parameters, return values

Such a function, reception parameters, while a return value, the following scenarios:

  • Internal function code remains the same, for the processing of different data different parameters , and return processing results desired
  • Such as card management system using the dictionary default values and prompt information prompts the user to enter content
    • If you enter, return to the input content
    • If you do not enter, return to the default value Dictionary

02. Advanced function's return value

  • Program development, sometimes, will want a function is executed after the end, tell the caller a result , for the caller to do follow-up treatment for concrete results
  • The return value is a function of the completion of the work , the last to the caller of a result
  • Used in the function returnkey can return results
  • Function call party may use the variable to the received function returns

Question: After the execution of a function can return multiple result?

Example - temperature and humidity measurements

  • Suppose you want to develop a function capable of simultaneously returns the current temperature and humidity
  • Return temperature to complete the following functions:
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, it is possible to return to the humidity
  • Transformation as follows:
def measure():
    """返回当前的温度"""

    print("开始测量...")
    temp = 39
    wetness = 10
    print("测量结束...")

    return (temp, wetness)

Tip: If a function returns a tuple, parentheses may be omitted

skill

  • In Pythonit can be a tuple will use an assignment statement while assigned to multiple variables
  • Note: The number of variables required and the number of tuples of elements consistent
result = temp, wetness = measure()

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

Method 1 - Use other variables

# 解法 1 - 使用临时变量
c = b
b = a
a = c

Method 2 - without the use of temporary variables

# 解法 2 - 不使用临时变量
a = a + b
b = a - b
a = a - b

Solution 3 - Python proprietary, using tuple

a, b = b, a

03. Advanced function parameters

3.1. Immutable and variable parameters

Question 1: Inside the function, the parameters used for the assignment , it will not affect the transfer of the function call argument variables ? - No!

  • Whether the parameter passed is variable or invariable
    • As long as the parameters for the use of an assignment statement , will the internal function to modify a local variable reference , will not affect the external variable references
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 parameter passed is the variable type , the internal functions, using the method to modify the content 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, a list of variables that call +=is essentially a list of variables in the implementation of the extendmethod 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)

3.2 default parameters

  • When you define a function, you can give a parameter to specify a default value , the parameter has a default value is called the default parameters
  • 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
  • For example: a method to sort 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)

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):

    gender_text = "男生"
    if not gender:
        gender_text = "女生"

    print("%s 是 %s" % (name, gender_text))

prompt

  1. The default parameters, need to use the most common value as the default value!
  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!

Notes default parameters

1) defines the location of the default parameters
  • Must ensure that the default parameters with default values at the end of the parameter list
  • So, the following definitions are wrong!
def print_info(name, gender=True, title):
2) calling a 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("老王", title="班长")
print_info("小美", gender=False)

Over 3.3 parameter (known)

Support for multi-parameter definition of function

  • Sometimes you may need a function parameter can handle the number is uncertain, at this time, you can use the multi-value parameter
  • pythonThere are two kinds of multi-value parameter:
    • Parameter name before increasing a * can receive tuple
    • Increase before the parameter name two * can receive 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*
  • argsIt is argumentsan abbreviation, meaning there are variables
  • kwIs keywordan abbreviation, kwargscan remember the key 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 be able to read Daniel code

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

demand

  1. Definition of a function sum_numbers, can receive any number of integers
  2. Functional requirements: the transfer of all the digital accumulation and returns accumulated result
def sum_numbers(*args):

    num = 0
    # 遍历 args 元组顺序求和
    for n in args:
        num += n

    return num

print(sum_numbers(1, 2, 3))

Tuples and dictionaries unpacking (know)

  • When calling functions with multi-value parameter, if you want:
    • A tuple variable , passed directly toargs
    • A dictionary variable , passed directly tokwargs
  • Can be used unpacking , simplified transmission parameters, unpacking way is:
    • In the former group of variables yuan , an increase of a *
    • In the dictionary of variables , increased 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. recursive function

Function calls itself a programming technique called recursion

Features 4.1 recursive function

Feature

  • A function internal call their own
    • Internal function can call other functions, of course, inside the function can also call their own

Code Features

  1. The internal function codes are identical except for the parameter different, different processing results
  2. When the parameters satisfy a condition , the function is not executed
    • This is very important , often referred to as a recursive export, otherwise there will be an infinite loop !

Sample Code

def sum_numbers(num):

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

    sum_numbers(num - 1)
    
sum_numbers(3)

4.2 recursive case - to calculate the figures for

demand

  1. The definition of a function sum_numbers
  2. Capable of receiving an numinteger parameter
  3. Calculation 1 + 2 + ... num of
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))

Tip: Recursion is a programming technique , the initial contact with recursion will feel some difficulty! In the process the loop conditions of uncertainty , particularly useful, for example: to traverse the entire file directory structure

Guess you like

Origin www.cnblogs.com/JcrLive/p/12235369.html