Python -- function 2 (variable scope, multi function execution process, return value, parameter, unpacking, reference, variable and immutable types)

abstract

  • Variable scope
  • Multi function program execution flow
  • Return value of function
  • Parameters of function
  • Unpack and exchange the values of two variables
  • quote
  • Variable and immutable types

1, Variable scope

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.

def testA():
    a = 100
    print(a)


testA()  # 100
print(a)  # Error: name 'a' is not defined

Variable a is a variable defined inside the testA function. If it is accessed outside the function, an error will be reported immediately.

Function of local variable: temporarily save data inside the function body, that is, destroy the local variable after the function call is completed.

  • global variable

The so-called global variable refers to the variable that can take effect both inside and outside the function.

Think: what if there is A data to be used in both function A and function B?

A: store this data in a global variable.

# Define global variable a
a = 100


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


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


testA()  # 100
testB()  # 100

Thinking: the testB function needs to modify the value of variable a to 200. How to modify the program?

a = 100


def testA():
    print(a)


def testB():
    a = 200
    print(a)


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

Think: is the variable a in a = 200 inside the testB function modifying the global variable a?

A: No. After observing the above code, it is found that the data of a obtained in line 15 is 100, which is still the value when defining the global variable a, and there is no return

200 inside the testB function. To sum up: a = 200 inside the testB function defines a local variable.

Thinking: how to modify global variables inside the function body?

Use the global keyword to declare that the location variable is a global variable

a = 100


def testA():
    print(a)


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


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

2, Multi function program execution flow

Generally, in the actual development process, a program is often composed of multiple functions (classes will be explained later), and multiple functions share some data, as shown below:

  • Shared global variables
# 1. Define global variables
glo_num = 0


def test1():
    global glo_num
    # Modify global variables
    glo_num = 100


def test2():
    # Call the modified global variable in test1 function
    print(glo_num)
    

# 2. Call test1 function and execute the internal code of the function: declare and modify global variables
test1()
# 3. Call test2 function and execute the internal code of the function: print
test2()  # 100
  • The return value is passed as a parameter
def test1():
    return 50


def test2(num):
    print(num)


# 1. Save the return value of function test1
result = test1()


# 2. Pass the variable of the function return value as a parameter to the test2 function
test2(result)  # 50

3, Return value of function

Think: if a function has two return s (as shown below), how does the program execute?

def return_num():
    return 1
    return 2


result = return_num()
print(result)  # 1

A: only the first return is executed because return can exit the current function, so the code below return will not be executed.

Think: if a function needs to have multiple return values, how to write code?

def return_num():
    return 1, 2


result = return_num()
print(result)  # (1, 2)

be careful:

  1. return a, b. when multiple data are returned, the default is tuple type.
  2. Return can be followed by a list, tuple, or dictionary to return multiple values.

4, Parameters of function

4.1 location parameters

Positional parameters: when calling a function, parameters are passed according to the parameter positions defined by the function.

def user_info(name, age, gender):
    print(f'What's your name{name}, Age is{age}, Gender is{gender}')
    
user_info('TOM', 20, 'male')

Note: the order and number of parameters passed and defined must be consistent.

4.2 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.

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


user_info('Rose', age=20, gender='female')
user_info('Xiao Ming', gender='male', age=16)

'''
Your name is ROSE, The age is 20, Gender is female
 Your name is Xiao Ming, The age is 18, Gender is male

'''

Note: when calling a function, if there is a location parameter, the location parameter must be in front of the keyword parameter, but there is no order between the keyword parameters.

4.3 default parameters

Default parameters are also called default parameters. They are used to define functions and provide default values for parameters. When calling a function, the value of the default parameter may not be passed (Note: all location parameters must appear in front of the default parameters, including function definition and call).

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


user_info('TOM', 20)
user_info('Rose', 18, 'female')

'''
Your name is TOM, The age is 18, Gender is male
 Your name is TOM, The age is 18, Gender is female
'''

Note: when calling a function, if the value is passed for the default parameter, the default parameter value will be modified; Otherwise, use this default value.

4.4 variable length parameters

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

Format: def function name (* args):

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

def user_info(*args):
    print(args)


user_info('TOM')
user_info('TOM', 20)
user_info('TOM', 20, 'man')
user_info()

'''
('TOM',)
('TOM', 20)
('TOM', 20, 'man')
()
'''
  • Package keyword delivery

Format: def function name (* * a):

Collect all keyword parameters and return a dictionary

def user_info(**kwargs):
    print(kwargs)
    
user_info()
user_info(name='TOM')
user_info(name='TOM', age=20)

'''
{}
{'name': 'TOM'}
{'name': 'TOM', 'age': 20}

'''

To sum up: both package location transfer and package keyword transfer are a process of package grouping.

5, Unpacking and exchanging variable values

5.1 unpacking

  • Unpacking: tuples
def return_num():
    return 100, 200


num1, num2 = return_num()
print(num1)  # 100
print(num2)  # 200
  • 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

5.2 exchange variable values

Demand: there are variables a = 10 and b = 20. Exchange the values of the two variables.

  • Method 1

The data is stored by means of a third variable.

# 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
a, b = 1, 2
a, b = b, a
print(a)  # 2
print(b)  # 1

6, Quote

6.1 understanding references

In python, values are passed by reference.

We can use id() to determine whether two variables are references to the same value. We can understand the id value as the address identification of that memory.

# 1. int type
a = 1
b = a

print(b)  # 1

print(id(a))  # 140708464157520
print(id(b))  # 140708464157520

a = 2
print(b)  # 1. Description: int type is immutable 

print(id(a))  # 140708464157552. At this time, the memory address of data 2 is obtained
print(id(b))  # 140708464157520


# 2. List
aa = [10, 20]
bb = aa

print(id(aa))  # 2325297783432
print(id(bb))  # 2325297783432


aa.append(30)
print(bb)  # [10, 20, 30], the list is of variable type

print(id(aa))  # 2325297783432
print(id(bb))  # 2325297783432

6.2 reference as argument

The code is as follows:

def test1(a):
    print(a)
    print(id(a))

    a += a

    print(a)
    print(id(a))


# int: the id value is different before and after calculation
b = 100
test1(b)

# List: the id values before and after calculation are the same
c = [11, 22]
test1(c)

'''
100
140708464160688
200
140708464163888
[11,22]
2008286519944
[11,22,11,22]
2008286519944

'''

The renderings are as follows:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-r5yqv7am-163124423690) (02 function II. assets/image-20190220111744493.png)]

7, Variable and immutable types

The so-called variable type and immutable type mean that data can be modified directly. If it can be modified directly, it is variable, otherwise it is immutable

  • Variable type
    • list
    • Dictionaries
    • aggregate
  • Immutable type
    • integer
    • float
    • character string
    • tuple

8, Summary

  • Variable scope
    • Global: functions can take effect both inside and outside the body
    • Local: the current function body takes effect internally
  • Function multiple return value writing method
return Expression 1, Expression 2...
  • Parameters of function
    • Position parameters
      • The number and writing order of formal parameters and arguments must be consistent
    • Keyword parameters
      • Writing method: key=value
      • Features: the writing order of formal parameters and arguments can be inconsistent; Keyword parameters must be written after positional parameters
    • Default parameters
      • The default parameter is the default parameter
      • Writing method: key=vlaue
    • Variable length position parameter
      • Collect all location parameters and return a tuple
    • Variable length keyword parameter
      • Collect all keyword parameters and return a dictionary
  • Reference: in Python, data is passed by reference

Keywords: Python

Added by autocolismo on Sat, 20 Nov 2021 19:51:07 +0200