1. 基本赋值
使用等号 =
进行赋值操作:
# 基本赋值示例 name = "Alice" # 字符串 age = 30 # 整数 height = 1.75 # 浮点数 is_student = True # 布尔值 print(f"{name} is {age} years old, {height}m tall. Student: {is_student}")
全面解析Python变量的赋值方法、特点及其独特优势
在Python中,变量是用来存储数据值的容器。与其他编程语言不同,Python变量不需要显式声明类型,解释器会根据赋值自动推断变量类型。
使用等号 =
进行赋值操作:
# 基本赋值示例 name = "Alice" # 字符串 age = 30 # 整数 height = 1.75 # 浮点数 is_student = True # 布尔值 print(f"{name} is {age} years old, {height}m tall. Student: {is_student}")
Python允许同时为多个变量赋值:
# 多重赋值示例 x, y, z = 10, 20, 30 print(f"x={x}, y={y}, z={z}") # 输出: x=10, y=20, z=30 # 交换变量值 a, b = 5, 10 a, b = b, a # 交换a和b的值 print(f"a={a}, b={b}") # 输出: a=10, b=5
为多个变量赋予相同的值:
# 链式赋值示例 m = n = p = 0 print(f"m={m}, n={n}, p={p}") # 输出: m=0, n=0, p=0
从序列中解包值到变量:
# 解包赋值示例 colors = ["red", "green", "blue"] color1, color2, color3 = colors print(color1) # 输出: red print(color2) # 输出: green print(color3) # 输出: blue # 使用*收集多余元素 first, *middle, last = [1, 2, 3, 4, 5] print(first) # 输出: 1 print(middle) # 输出: [2, 3, 4] print(last) # 输出: 5
Python变量是动态类型的,同一个变量可以在不同时间引用不同类型的对象:
# 动态类型示例 value = 100 # 整数 print(type(value)) # 输出: <class 'int'> value = "Python" # 字符串 print(type(value)) # 输出: <class 'str'> value = [1, 2, 3] # 列表 print(type(value)) # 输出: <class 'list'>
优势: 提高代码灵活性,简化开发过程。
Python使用引用计数和垃圾回收机制自动管理内存:
# 自动内存管理示例 def create_list(): # 创建一个大列表 big_list = list(range(1000000)) return big_list # 函数调用结束后,big_list不再被引用,内存会自动回收 result = create_list() print("内存已自动回收")
优势: 避免内存泄漏,减少手动内存管理的复杂性。
Python变量存储的是对象的引用,而不是对象本身:
# 引用语义示例 list1 = [1, 2, 3] list2 = list1 # list2和list1引用同一个列表对象 list2.append(4) print(list1) # 输出: [1, 2, 3, 4] (list1也被修改) # 创建副本 list3 = list1.copy() # 或 list3 = list1[:] list3.append(5) print(list1) # 输出: [1, 2, 3, 4] (list1未改变) print(list3) # 输出: [1, 2, 3, 4, 5]
优势: 提高效率,便于实现复杂数据结构。
Python使用命名空间管理变量,作用域规则清晰:
# 作用域示例 global_var = "I'm global" def test_function(): local_var = "I'm local" print(global_var) # 可以访问全局变量 print(local_var) # 访问局部变量 test_function() # print(local_var) # 报错: NameError,无法在函数外访问局部变量
优势: 避免命名冲突,提高代码可维护性。
student_count
比 sc
更好list
, str
, dict
等MAX_SIZE = 100
# 类型提示示例 (Python 3.6+) def calculate_total(items: list, discount: float = 0.0) -> float: """计算商品总价""" subtotal = sum(item['price'] for item in items) total = subtotal * (1 - discount) return total # 使用示例 products = [{'name': 'Book', 'price': 25.50}, {'name': 'Pen', 'price': 3.75}] final_price = calculate_total(products, 0.1) print(f"Total after discount: ${final_price:.2f}")
本文由JiHuiZhen于2025-08-16发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://www.521pj.cn/20258279.html
发表评论