Python 变量类型
Python 变量类型
Section titled “Python 变量类型”变量是编程中的基本概念,它们充当命名容器,用于在内存中存储数据值。当你创建 Python 变量时,你就是在为它将要持有的数据预留内存空间。
Python 是动态类型的语言,这意味着你无需事先显式声明变量的类型。解释器会根据赋给变量的值自动确定其类型。
使用赋值运算符 (=) 给变量赋值。变量名在左边,值在右边。
# Variable assignmentscounter = 100 # An integer assignmentpi_value = 3.14159 # A floating-point assignmentname = "Alice" # A string assignmentis_active = True # A boolean assignmentmy_list = [1, 2, 3] # A list assignment
# Using the variablesprint(counter)print(pi_value)print(name)print(is_active)print(my_list)输出:
1003.14159AliceTrue[1, 2, 3]Python 允许同时给多个变量赋值一个相同的值:
x = y = z = 0 # All three variables reference the same integer object 0print(x, y, z)你也可以在一行中给多个变量赋不同的值(常用于解包序列):
a, b, city = 1, 2.5, "New York"print(a) # Output: 1print(b) # Output: 2.5print(city) # Output: New York标准数据类型
Section titled “标准数据类型”Python 内置了几种数据类型,它们定义了变量可以持有的数据种类以及可以对其执行的操作。主要的标准类型包括:
- 数值类型:
int(整型)、float(浮点型)、complex(复数) - 序列类型:
str(字符串)、list(列表)、tuple(元组) - 映射类型:
dict(字典) - 集合类型:
set(集合)、frozenset(不可变集合) - 布尔类型:
bool(布尔型) - 二进制类型:
bytes(字节串)、bytearray(字节数组)、memoryview(内存视图) - 空值类型:
NoneType(只有一个值:None)
数值类型 (int, float, complex)
Section titled “数值类型 (int, float, complex)”存储数值。它们是不可变 (immutable) 的。
int_var = 10float_var = 12.5complex_var = 3 + 4j
# Deleting variable referencesdel float_var# print(float_var) # Would raise NameError序列类型 (str, list, tuple)
Section titled “序列类型 (str, list, tuple)”表示有序的项集合。
字符串示例:
Section titled “字符串示例:”my_str = 'Hello World!'
print(my_str) # Output: Hello World!print(my_str[0]) # Output: H (First character)print(my_str[6:11]) # Output: World (Slice from index 6 up to 11)print(my_str[6:]) # Output: World! (Slice from index 6 to end)print(my_str * 2) # Output: Hello World!Hello World!print(my_str + " Python") # Output: Hello World! Pythonmy_list = ['abcd', 786, 2.23, 'john', 70.2]tiny_list = [123, 'john']
print(my_list) # Output: ['abcd', 786, 2.23, 'john', 70.2]print(my_list[0]) # Output: abcdprint(my_list[1:3]) # Output: [786, 2.23]print(my_list[2:]) # Output: [2.23, 'john', 70.2]print(tiny_list * 2) # Output: [123, 'john', 123, 'john']print(my_list + tiny_list) # Output: ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
# Lists are mutablemy_list[2] = 'updated'print(my_list) # Output: ['abcd', 786, 'updated', 'john', 70.2]my_tuple = ('abcd', 786, 2.23, 'john', 70.2)tiny_tuple = (123, 'john')
print(my_tuple) # Output: ('abcd', 786, 2.23, 'john', 70.2)print(my_tuple[0]) # Output: abcdprint(my_tuple[1:3]) # Output: (786, 2.23)print(my_tuple[2:]) # Output: (2.23, 'john', 70.2)print(tiny_tuple * 2) # Output: (123, 'john', 123, 'john')print(my_tuple + tiny_tuple) # Output: ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
# Tuples are immutable# my_tuple[2] = 1000 # This would raise a TypeError映射类型 (dict)
Section titled “映射类型 (dict)”dict (Dictionary,字典): 可变的独特键-值对集合。使用花括号 {} 定义。键必须是不可变类型(如字符串、数字、元组)。值可以是任何类型。在旧版本 Python 中,字典是无序的,但在 Python 3.7+ 中,它们保持插入顺序。
my_dict = {}dict_one = {'name': 'john', 'code': 6734, 'dept': 'sales'}
my_dict['one'] = "This is value one"my_dict[2] = "This is value two"
print(my_dict['one']) # Output: This is value oneprint(my_dict[2]) # Output: This is value twoprint(dict_one) # Output: {'name': 'john', 'code': 6734, 'dept': 'sales'}print(dict_one.keys()) # Output: dict_keys(['name', 'code', 'dept'])print(dict_one.values()) # Output: dict_values(['john', 6734, 'sales'])集合类型 (set, frozenset)
Section titled “集合类型 (set, frozenset)”表示无序的独特、不可变项集合。用于成员测试、去除重复项以及集合操作(并集、交集等)。
my_set = {1, 2, 3, 2, 1} # Duplicates are automatically removedprint(my_set) # Output: {1, 2, 3} (Order may vary)
empty_set = set()print(empty_set) # Output: set()
frozen = frozenset(["a", "b", "c"])print(frozen) # Output: frozenset({'c', 'a', 'b'})# frozen.add("d") # AttributeError: 'frozenset' object has no attribute 'add'布尔类型 (bool)
Section titled “布尔类型 (bool)”表示真值。只有两个可能的值:True 和 False(注意大小写)。通常是比较或逻辑操作的结果。
is_valid = Truehas_error = Falseprint(is_valid) # Output: Trueprint(5 > 3) # Output: Trueprint(type(False)) # Output: <class 'bool'>空值类型 (NoneType)
Section titled “空值类型 (NoneType)”表示没有值。只有一个值:None。常用于默认值或占位符。
result = Noneprint(result) # Output: Noneprint(type(None)) # Output: <class 'NoneType'>数据类型转换
Section titled “数据类型转换”通常可以使用以目标类型命名的内置函数在数据类型之间进行转换。
| 函数 | 描述 |
|---|---|
int(x [,base]) | 将 x 转换为整数。如果 x 是字符串,base 指定基数(例如,int('101', 2))。 |
float(x) | 将 x 转换为浮点数。 |
str(x) | 将对象 x 转换为字符串表示。 |
list(s) | 将可迭代对象 s 转换为列表。 |
tuple(s) | 将可迭代对象 s 转换为元组。 |
set(s) | 将可迭代对象 s 转换为集合。 |
dict(d) | 创建字典。d 可以是 (键, 值) 对的序列或关键字参数。 |
bool(x) | 将 x 转换为布尔值。对于 0、None、空序列/映射,返回 False;否则返回 True。 |
complex(real [,imag]) | 创建复数。 |
bytes(source [, encoding]) | 创建不可变的字节串对象。 |
chr(i) | 将整数 i 转换为其对应的 Unicode 字符。 |
ord(c) | 将单个字符 c 转换为其整数 Unicode 码点。 |
hex(x) | 将整数转换为小写的十六进制字符串,前缀为 “0x”。 |
oct(x) | 将整数转换为八进制字符串,前缀为 “0o”。 |
注意:Python 2 中的 long() 函数已被移除;int 处理任意大小的整数。eval() 会将字符串作为 Python 代码求值,使用时务必极端小心,因为它存在安全风险。repr() 提供对象的明确字符串表示,通常可用于重新创建对象。