Skip to content

基本语法

变量

基本语法

变量名 = xxx

python
# 整数变量 (Integer variable)
age = 30

# 浮点数变量 (Floating-point variable)
price = 99.99

# 字符串变量 (String variable)
name = "张三"

# 布尔值变量 (Boolean variable)
is_student = True

# 列表变量 (List variable)
my_list = [1, 2, 3, "Python"]

# 你可以随时改变变量存储的值及其类型 (动态类型 Dynamic Typing)
x = 10         # x 现在是整数 (x is now an integer)
print(type(x)) # 输出: <class 'int'>

x = "你好"     # x 现在是字符串 (x is now a string)
print(type(x)) # 输出: <class 'str'>

多重赋值

同一个值赋给多个变量

python
a = b = c = 100
print(a) # 输出: 100
print(b) # 输出: 100
print(c) # 输出: 100

将多个值分别赋给多个变量

python
x, y, z = 10, 20, "hello"
print(x) # 输出: 10
print(y) # 输出: 20
print(z) # 输出: hello

# 常用于交换变量值
x, y = y, x
print(x) # 输出: 20
print(y) # 输出: 10

作用域

查找顺序,LEGB 规则

  • L (Local): 局部作用域
  • E (Enclosing function locals): 闭包函数外的函数作用域
  • G (Global): 全局作用域
  • B (Built-in): 内置作用域

局部变量

函数参数,函数内定义的变量

闭包函数作用域

函数嵌套,内部函数可以访问外部(但非全局)函数的变量。这个外部函数的范围就是内部函数的“闭包函数作用域”。

python
def outer_function():
    # outer_var 在外层函数的局部作用域,但在内层函数的闭包作用域
    outer_var = "I am outer"

    def inner_function():
        # 内部函数可以访问外部函数的变量
        print(outer_var)

    inner_function()  # 调用内部函数


outer_function()  # 输出: I am outer