python function 2_ variable scope, function parameters (positional parameters, keyword parameters, default parameters, variable length positional parameters, variable length keyword parameters), unpacking, reference

I wrote a function before, there should be a total of 3 articles about the function, and I will post it here when I write it

0. Content

  • variable scope
  • Multi-Function Program Execution Flow
  • function return value
  • function parameters
  • Unpack and swap the values ​​of two variables
  • quote
  • mutable and immutable types

1. Variable scope

The variable scope refers to the range in which the variable takes effect. It is mainly divided into two categories: local variables and global variables.

1.1 Local variables

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, and if accessed outside the function, an error will be reported immediately.

The role of local variables: inside the function body, the data is temporarily saved, that is, when the function call is completed, the local variables are destroyed.

1.2 Global variables (exactly the same as C language when there is no class)

The so-called global variables refer to variables that can take effect both inside and outside the function body.

Thinking: What should I do if there is a piece of data that is used in both function A and function B?

Answer: Store this data in a global variable.

# define a global variable
a = 100

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

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

testA()  # 100
testB()  # 100

Thinking 1: 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 # It is equivalent to defining a new local variable by yourself, shielding the outer global variable, and the global variable a has not been changed
    print(a)

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


Thinking 2: Is the variable a in a = 200 inside the testB function modifying the global variable a?

Answer: No. Observing the above code, it is found that the data of a obtained in line 15 is 100, which is still the value when the global variable a is defined, and does not return

Modify the value of the global variable in the function body

Thinking 3: How to modify global variables inside the function body?

a = 100

def testA():
    print(a)

def testB():
    # The 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 in the knowledge), and multiple functions share some data, as shown below:

2.1 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 the test1 function
    print(glo_num)
    

# 2. Call the test1 function and execute the internal code of the function: declare and modify global variables
test1()
# 3. Call the test2 function and execute the internal code of the function: print
test2()  # 100

2.2 The return value is passed as a parameter

def test1():
    return 50


def test2(num):
    print(num)


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


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

3. The return value of the function

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

Answer: Only the first return is executed, because the return can exit the current function, so the code below the return is not executed.

Thinking: If a function has multiple return values, how to write the code?

def return_num():
    return 1, 2

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

Notice:

  1. return a, b is written. When returning multiple data, the default is a tuple type.
  2. Lists, tuples, or dictionaries can be concatenated after return to return multiple values.

4. Function parameters

4.1 Positional parameters

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

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

user_info('TOM', 20, 'male') # Your name is TOM, your age is 20, your gender is male

Note: The order and number of passing and defining parameters must be consistent.

4.2 Keyword arguments

Function calls, specified as key=value. It can make the function clearer and easier to use, and it also removes the order requirements of the parameters.

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

user_info('Rose', age=20, gender='Female')
user_info('Xiao Ming', gender='male', age=16) # ★

Note: When the function is called, if there are positional parameters, the positional parameters must be in front of the keyword parameters, but there is no sequence between the keyword parameters.

4.3 Default parameters

Default parameters are also called default parameters, which 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 positional parameters must appear before the default parameter, including function definition and call).

def user_info(name, age, gender='male'):
    print(f'your name is{name}, age is{age}, sex is{gender}')

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

Note: When the function is called, if the default parameter value is passed, the default parameter value will be modified; otherwise, the default value will be used.

4.4 Indefinite length parameters

Indefinite length parameters are also called variable parameters. It is used in scenarios where it is uncertain how many parameters will be passed when calling (it is also possible to pass no parameters). At this time, it will be very convenient to use packing positional parameters or packing keyword parameters for parameter passing.

1) Package location transfer (collection type)

def user_info(*args):
    print(args)

user_info('TOM') # ('TOM',)
user_info('TOM', 18) # ('TOM', 18)

Note: All the 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 the position of the package.

2) Wrap keyword delivery (dictionary type)

def user_info(**kwargs):
    print(kwargs)

user_info(name='TOM', age=18, id=110) # {'name': 'TOM', 'age': 18, 'id': 110}

To sum up: Whether it is the delivery of the package location or the delivery of the package keyword, it is a process of grouping packages.

  • Access to the dictionary Pay attention to the usage. By default, only the key is unpacked from the dictionary
def user_info(**kwargs):
    print(type(kwargs))
    for i in kwargs:
        print(i,kwargs[i])

user_info(name='TOM', age=18, id=110) # {'name': 'TOM', 'age': 18, 'id': 110}

5. Unpacking and swapping 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
    The dictionary unpacked is just the key
dict1 = {'name': 'TOM', 'age': 18}
a, b = dict1

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

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

5.2 Swap variable values

Requirement: There are variables a = 10 and b = 20, exchange the values ​​of the two variables.

  • Method 1 Low-level approach of c and java

Data is stored with the aid of a third variable.

# 1. Define intermediate variables
c = 0

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

# 3. Assign the data 20 of b to a, at this time a = 20
a = b

# 4. Assign the previous data 10 of c to b, at this time b = 10
b = c

print(a)  # 20
print(b)  # 10
  • Method 2 python is so convenient
a, b = 1, 2
print(a,b) # 1 2

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

6. Citation

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 identifier of that piece of memory.

1) int type (immutable type)

a = 1
b = a

print(b)  # 1  
# a,b same block of memory
print(id(a))  # 1887241005360
print(id(b))  # 1887241005360

a = 2 # a has new memory
print(b)  # 1, indicating that the int type is an immutable type 
# a and b have different memory (after reassigning the immutable type, it is equivalent to redefining a new variable with new memory)
print(id(a))  # 1887241005392, now get the memory address of data 2
print(id(b))  # 1887241005360

2) List type (variable type)

aa = [10, 20]
bb = aa
# aa, bb same memory (equivalent to a variable)
print(id(aa))  # 1887370401344
print(id(bb))  # 1887370401344


aa.append(30) # aa and bb are still the same memory ★
print(bb)  # [10, 20, 30], the list is mutable,
# aa and bb are the same block of memory, aa changes, bb also changes

print(id(aa))  # 1887370401344
print(id(bb))  # 1887370401344

6.2 References as arguments

code show as below:

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

    a += a

    print(a)
    print(id(a))


# int: different id values ​​before and after calculation 
b = 100
test1(b)

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

== The id value is different after the immutable type is modified ==
After the variable type is modified, the id value is the same

Seven. Mutable and immutable types ▲

The so-called variable type and immutable type refer to: the data can be directly modified, if it can be directly modified, it is variable, otherwise it is immutable.

  • mutable type
    • the list
    • dictionary
    • gather
  • immutable type
    • integer
    • floating point
    • string
    • tuple

8. Summary

  • variable scope
    • Global: It can take effect inside and outside the function body
    • Local: takes effect inside the current function body
  • How to write function with multiple return values
return expression 1, expression 2...
  • function parameters
    • positional parameters
      • The number and writing order of formal parameters and actual parameters must be consistent
    • keyword arguments
      • Writing method: key=value
      • Features: The writing order of formal parameters and actual parameters can be inconsistent; keyword parameters must be written after positional parameters
    • default parameters
      • Default parameters are default parameters
      • Writing: key=vlaue
    • indefinite positional parameters
      • Collect all positional arguments, return a tuple
    • variable-length keyword arguments
      • Collect all keyword arguments, return a dictionary
  • References: In Python, data is passed by reference

Tags: Python programming language

Posted by m4x3vo on Mon, 14 Nov 2022 22:48:37 +0300