python basis _ advanced functions

Advanced Functions

aims

  • Role of function arguments and return values
  • The return value of the function Advanced
  • Function parameters Advanced
  • 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

  • No parameters and returns no value
  • No parameters, return values
  • There are parameters, no return value
  • There are parameters, return values

python basis _ advanced functions

Defining a function, whether the received parameters, return results or whether , based on the actual functional requirements to decide!

  • If the function data uncertain internal processing , the data may be passed to the outside in the internal parameter function
  • 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:

  • Just simply do one thing , for example, to display the menu
  • 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
  • Use the return keyword to return results in the function
  • Function call party may use the variable to the received function returns

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 Python may be a tuple to use assignment statements simultaneously assigned to a plurality of 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

  • There are two integer variables a = 6, b = 100
  • Without using other variables, values of two variables exchanged
    Method 1 - Use of 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 actual parameter passing of function call? - No!

  • Whether the parameter passed is variable or invariable
    • As long as the parameters for the use of an assignment statement , will modify local variables inside a function reference , it 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 on calling + = essentially extend the implementation of the method in the list of variables, 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 specify a default value for a parameter , 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 parameters of the function, the value of the common set to the default parameters, thereby simplifying the function call
    , for example: a 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)

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

  • The default parameters, need to use the most common value as the default value!
  • If a parameter value can not be determined , it should not set a default value , specific value when you call the function, passing by the outside world!

Notes default parameters
define the position 1) 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

  • When calling the function, if there are multiple 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("xm")
print_info("lb", title="monitor")
print_info("xm", gender=False)

Over 3.3 parameter (known)

Support for multi-parameter definition of function

  • Sometimes the number of parameters may need to be able to handle a function is uncertain, at this time, you can use the multi-value parameter
  • python, there are two multi-value parameter:
    • * Before adding a parameter name can receive tuples
    • Parameter name before adding two * can receive Dictionary
  • Generally when a multi-value parameter named, accustomed to using the two names

  • * Args - storing tuples parameters, preceded by a *
  • ** kwargs - dictionary storage parameters, there are two front *
  • args is an abbreviation arguments, there is a variable meaning
  • kw is the keyword abbreviations, kwargs can remember the key parameters
def demo(num, *args, **kwargs):

    print(num)
    print(args)
    print(kwargs)

demo(1, 2, 3, 4, 5, name="xm", age=18, gender=True)

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

demand

  • Define a plurality of integer function any sum_numbers, can receive
  • Functional requirements: the transfer and return all the figures for 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 to args
    • A variable dictionary, passed directly to kwargs
  • Unpacking can be used to simplify the transmission parameters, unpacking it is:
    • Before tuple variable, add a *
    • Before dictionary variable, add two *
def demo(*args, **kwargs):

    print(args)
    print(kwargs)

# 需要将一个元组变量/字典变量传递给函数对应的参数
gl_nums = (1, 2, 3)
gl_xm = {"name": "xm", "age": 18}

# 会把 num_tuple 和 xm 作为元组传递个 args
# demo(gl_nums, gl_xm)
demo(*gl_nums, **gl_xm)

04. recursive function

Function calls itself a programming technique called recursion

Features 4.1 recursive function

Feature

  • An internal function call their own
    • Internal function can call other functions, of course, inside the function can also call their own
      codes Features
  • The internal function code is the same, except for the different parameters, a different result of the processing
  • When the parameters satisfy a condition, the function is not executed
    • This is very important, often called recursive exports, there would be an infinite loop!
      Sample Code
def sum_numbers(num):

    print(num)

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

    sum_numbers(num - 1)

sum_numbers(3)

python basis _ advanced functions

4.2 recursive case - to calculate the figures for

demand

  • Define a function sum_numbers
  • Capable of receiving a num of the integer parameter
  • 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))

python basis _ advanced functions

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 blog.51cto.com/tobeys/2442746