数据类型


int 整型:

print(3 + 7)          # 整数运算,结果 10
print(type(42))       # type()函数用于查看参数的数据类型 输出<class 'int'>  表示“整型”
print(1_000_000)      # 下划线只是写给人看的,方便阅读,值仍是 1000000

float 浮点型:

print(15 / 4)         # 除法得到小数,结果 3.75
print(type(3.14))     # <class 'float'>
print(2.0 + 1)        # 整型+浮点→自动变浮点 3.0

str 字符串:

print('hello world')  #字符串,使用单引号或双引号包围
print('hello' + 'world')  # 拼接,结果 helloworld
print(type('abc'))        # <class 'str'>
print("It's 3.3 V")       # 双引号可包单引号,避免冲突

bool 布尔型:

print(True and False)  # 逻辑与,结果 False
print(type(5 > 3))     # <class 'bool'>
print(int(True))       # 把布尔转整数,True→1,False→0

list 列表:

nums = [1, 2, 3]
print(nums + [4, 5])   # 合并,结果 [1, 2, 3, 4, 5]
print(type(nums))      # <class 'list'>
print(nums * 2)        # 重复,结果 [1, 2, 3, 1, 2, 3]

tuple 元组:

point = (10, 20)
print(point + (30, 40))  # 合并,结果 (10, 20, 30, 40)
print(type(point))       # <class 'tuple'>
# 单元素要加逗号:(100,) 才是元组,否则只是普通括号

bytes 字节型:

data = b'HELLO'        # 前面加 b,每个字符占 1 字节
print(type(data))      # <class 'bytes'>
print(data[0])         # 输出 72,对应 ASCII 码的 'H'

bytearray 可变字节:

buf = bytearray(4)     # 生成 4 个 0 的可改字节串
buf[0] = 0x55          # 可像列表一样改值
print(type(buf))       # <class 'bytearray'>

None 空值:

a = None               # 表示“什么都没有”
print(type(a))         # <class 'NoneType'>
# 常用来给函数当“还没返回”的占位值