Python variables

Article directory

overview

Variables can be used without definition, but before using a variable, you must explicitly give the variable a value

Code example:

name = 'Tom'
print(name)

result:

Tom

The variable consists of three parts:
ID: indicates the memory address stored by the object, and uses the built-in function id(obj) to obtain
Type: indicates the data type of the object, and uses the built-in function type(obj) to obtain
the value: indicates the object stored For specific data, use print(obj) to print out the value

Code example:

name = 'Tom'
print('标识:', id(name))
print('类型:', type(name))
print('值:', name)

result:

标识: 2862007583216
类型: <class 'str'>
值: Tom

After multiple assignments, the variable will point to the new space

Code example:

name = 'Bob'
print('标识:', id(name))
print('类型:', type(name))
print('值:', name)

result:

标识: 2862007583152
类型: <class 'str'>
值: Bob

It turns out that the memory occupied by Tom is not used by variables and becomes garbage memory, which is recycled by Python's garbage collection mechanism

Code example:

print('标识:', id('令狐冲'))
print('类型:', type('令狐冲'))
print('值:', '令狐冲')

result:

标识: 2862007652496
类型: <class 'str'>
值: 令狐冲

variable scope

Divided into global variables and local variables

Local variable: The variable defined and used in the function is only valid inside the function. If the local variable is declared with global, then the variable becomes a global variable

Global variables: Variables defined outside the function, can be used in the function

def fun(a, b):
    c = a + b
    return c


# 函数形参 a 和 b 和函数体内定义的变量 c 都是局部变量

age = 10    # 全局变量
print(age)  # 函数体外使用全局变量


def fun2():
    print(age)  # 函数体内使用全局变量


fun2()


def fun3():
    global name
    name = 'Tom'


fun3()
print(name)  # 这里需要先执行一下 fun3(), 否则 name 没有值, 输出会报错

result:

10
10
Tom

Guess you like

Origin blog.csdn.net/chengkai730/article/details/132199421