day10_ Elementary knowledge of function

Keywords: Python

Concept and definition of function

What is a function?

Function is to integrate a piece of code block with independent functions into a whole and name it, and call the name where needed to complete the corresponding requirements. In the development process of function, code reuse can be realized more efficiently.

characteristic:

  • In Python, functions must be defined before use. The function does not call or execute.   When defining a function, the code indented inside the function body is not executed
  • The function is called first and executed first.

How to define functions

Calling function: function name (parameter)  

Code example

# Define function
def select_func():
    print('-----Please select a function-----')
    print('Check the balance')
    print('deposit')
    print('withdraw money')
    print('-----Please select a function-----')


# Call function
select_func()

Function execution process

  • When calling a function, the interpreter returns to the place where the function is defined to execute the code indented below. When these codes are executed, it returns to the place where the function is called and continues to execute downward.

Parameters of function

The function can receive external data through parameters, making the function more flexible

# When defining the function, the parameters a and b for receiving user data are defined at the same time. A and b are formal parameters
def sum_number(a, b):
    print(a + b)


# When calling the function, real data 2 and 4 are passed in, and the real data is an argument
sum_number(2, 4)

The number of line parameters of the defined function and the number of actual parameters of the calling function should correspond one by one. For example, the definition function has 2 parameters, and the incoming data should also be 2.

Position parameters

When calling a function, parameters are passed according to the parameter positions defined by the function. The order and number of parameters passed and defined must be consistent.

def test(name, age, sex):
    print(f'What's your name{name}, Age is{age}, Gender is{sex}')


test("Zhang San", 28, "male")

Keyword parameters

Function call, specified in the form of "key = value". It can make the function clearer and easier to use, and eliminate the sequence requirements of parameters. When calling a function, if there is a positional parameter, the positional parameter must precede the keyword parameter, but there is no order between the keyword parameters.

def test(name, age, sex):
    print(f'What's your name{name}, Age is{age}, Gender is{sex}')


test("Zhang San", sex="male", age=88)

Default parameters

Default parameters are also called default parameters. They are used to define functions and provide default values for parameters. The value of the default parameter may not be passed when calling a function. All positional parameters must appear before the default parameters, including function definitions and calls. When calling a function, if the value is passed for the default parameter, modify the default parameter value; Otherwise, use this default value.

def test(name, age, sex="male"):
    print(f'What's your name{name}, Age is{age}, Gender is{sex}')


test("Zhang San", age=88)

Indefinite length parameter

Variable length parameters are also called variable parameters. It is used in scenarios where it is uncertain how many parameters will be passed during the call (it is OK not to pass parameters). At this time, it is very convenient to transfer the parameters by using the packaging location parameter or the package keyword parameter.

Package location transfer: all parameters passed in will be collected by the args variable, which will be combined into a tuple according to the location of the parameters passed in. Args is a tuple type, which is package location transfer.

def test(*args):
    print(args)  # (1, 2, 3)
    print(type(args))  # <class 'tuple'>


test(1, 2, 3)

Package keyword transfer: all parameters passed in will be collected by the kwargs variable, which will be combined into a dictionary (dict) according to the location of the passed in parameters. Kwargs is a dictionary type, which is package location transfer.

def user_info(**kwargs):
    print(kwargs)  # {'name': 'TOM', 'age': 18, 'id': 110}
    print(type(kwargs))  # <class 'dict'>

user_info(name='TOM', age=18, id=110)

Whether it is package location transfer or package keyword transfer, it is a process of package grouping.  

Return value of function

The function can return the result of the function operation to the function call through the return value, which is convenient for subsequent data processing. The return value of a function can be passed as another parameter.

# When defining the function, the parameters a and b for receiving user data are defined at the same time,
def sum_number(a, b):
    # Return result to function call
    return a + b


# Function return result received
result = sum_number(2, 4)
print(f"The calculation result is{result}")

return function:

  • Responsible for function return value
  • Exit the current function: this causes all the code below return (inside the function body) not to be executed

What if you need to return multiple data?

Return can be followed by a list, tuple, or dictionary to return multiple values.

def return_num():
    # return a, b. when multiple data are returned, the default is tuple type
    return 1, 2


result = return_num()
print(type(result))  # <class 'tuple'>
print(result)  # (1, 2)

Documentation for functions

The function description document is also called the function description document. Function: convenient to view the introduction of functions. Example documentation for defining functions:

def sum_number(a, b):
    """
    Summation function
    :param a: Calculation parameter Number1
    :param b: Calculation parameter number2
    :return:  2 Sum of two numbers
    """
    return a + b


# View function description document
help(sum_number)

Function nested call

Nested function call means that another function is called in one function. If a function B is called in function A, then the task in function B is executed before the last function A executes.

Example

def testB():
    print('---- testB start----')
    print('Here is testB Code executed by function...(ellipsis)...')
    print('---- testB end----')


def testA():
    print('---- testA start----')
    testB()
    print('---- testA end----')


testA()

Execution example

  Function nesting exercise

def get_sum(a, b, c):
    """ Find the sum of three numbers  """
    return a + b + c


def average_num(a, b, c):
    """Average the three numbers"""
    result = get_Sum(a, b, c)
    return result / 3


print(average_num(3, 6, 9)) #6.0

Scope of variable

Variable scope refers to the effective range of variables, which is mainly divided into two categories: local variables and global variables.

local variable

  • The so-called local variables are variables defined inside the function body, that is, they only take effect inside the function body.
  • Function of local variable: temporarily save data inside the function body, that is, destroy the local variable after the function call is completed.
def test():
    a = 10  # local variable
    print(a)


test()
print(a)  # NameError: name 'a' is not defined

global variable

The so-called global variable is defined outside the function. Variables that can take effect both inside and outside the function.

# Define global variable a
a = 100


def test1():
    print(a)  # Access global variable a and print the data stored in variable a


def test2():
    print(a)  # Access global variable a and print the data stored in variable a


test1()  # 100
test2()  # 100

How to modify a global variable inside a function body

Use the global keyword to declare variables

a = 100


def testB():
    # Global keyword declares that a is a global variable
    global a
    a = 200
    print(a)  # 200

testB()  # 200
print(f'global variable a = {a}')  # Global variable a = 200

Unpacking and exchanging variable values

Unpacking is the process of taking out the data in the container one by one.

Unpacking: tuples

# Unpacking: return value of function
def test(a, b):
    c = a + b
    e = a - b
    return c, e


c, e = test(3, 5)
print(c)  # 8
print(e)  # -2

Unpacking: Dictionary

dict1 = {'name': 'TOM', 'age': 18}
a, b = dict1

# Unpack the dictionary and take out the key of the dictionary
print(a)  # name
print(b)  # age

print(dict1[a])  # TOM
print(dict1[b])  # 18

Exchange variable values

Method 1

# 1. Define intermediate variables
c = 0

# 2. Store the data of a to c
c = a

# 3. Assign the data 20 of b to a, where a = 20
a = b

# 4. Assign the data 10 of the previous c to B, where b = 10
b = c

print(a)  # 20
print(b)  # 10

Method 2 (recommended)

a = 1
b = 2
a, b = 2, 1
print(a)  # 2
print(b)  # 1

Posted by dagon on Sat, 30 Oct 2021 20:59:45 -0700