首页 / 知识库 / 0基础入门-阅读资料 / 0基础-python入门到精通

第 2 章 基本数据类型

2.1 数字类型:int、float、complex

Python 有三种内置数字类型:

int — 整数

a = 42
b = -17
c = 0

# 不同进制表示
binary    = 0b1010   # 二进制 → 10
octal     = 0o17     # 八进制 → 15
hex_num   = 0xFF     # 十六进制 → 255

# 大数字可用下划线分隔,提高可读性
population = 1_400_000_000

float — 浮点数

pi = 3.14159
e = 2.718
speed_of_light = 3e8      # 科学记数法 → 300000000.0
tiny = 1.6e-19             # → 0.00000000000000000016

# float 和 int 运算,结果为 float
result = 10 + 3.0          # 13.0

complex — 复数

z = 3 + 4j
print(z.real)    # 3.0
print(z.imag)    # 4.0
print(abs(z))    # 5.0 — 模

类型转换

int(3.9)       # 3 — 截断,不是四舍五入
int("42")      # 42
float("3.14")  # 3.14
float(10)      # 10.0

2.2 任意精度整数与浮点数精度陷阱

整数:无限精度

Python 的 int 没有大小限制,可以表示任意大的整数:

huge = 2 ** 1000
print(huge)
# 1071508607186267320948425049060001810561404811705...(很长的数字)

import sys
# int 没有固定字节数,大小随值增长
print(sys.getsizeof(0))        # 28 字节
print(sys.getsizeof(2**30))    # 32 字节
print(sys.getsizeof(2**1000))  # 160 字节

浮点数:IEEE 754 双精度,有精度限制

# 经典陷阱
print(0.1 + 0.2)           # 0.30000000000000004
print(0.1 + 0.2 == 0.3)    # False !

# 原因:0.1 在二进制中是无限循环小数,存储时被截断

解决方案

# 方案 1:使用 math.isclose 近似比较
import math
print(math.isclose(0.1 + 0.2, 0.3))  # True

# 方案 2:使用 decimal 模块精确运算
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))  # 0.3(精确)
# 注意:必须用字符串初始化,Decimal(0.1) 仍然不精确

# 方案 3:处理金额时用整数(单位为分)
price_cents = 199  # 1.99 元

fractions — 精确的分数

from fractions import Fraction

f = Fraction(1, 3)
print(f)                # 1/3
print(f + Fraction(1, 6))  # 1/2
print(float(f))         # 0.3333333333333333

2.3 布尔类型 bool 与真值判断

boolint 的子类,只有两个值:True(1)和 False(0)。

print(isinstance(True, int))  # True
print(True + True)             # 2
print(True * 10)               # 10

真值判断(Truthiness)

Python 中任何对象都可以判断真假。以下值为 假(Falsy)

# 所有"空"和"零"都是 False
bool(False)     # False
bool(None)      # False
bool(0)         # False
bool(0.0)       # False
bool(0j)        # False
bool("")        # False — 空字符串
bool([])        # False — 空列表
bool(())        # False — 空元组
bool({})        # False — 空字典
bool(set())     # False — 空集合

其他所有值为 真(Truthy)

bool(1)         # True
bool(-1)        # True — 非零即真
bool("hello")   # True
bool([0])       # True — 非空列表(哪怕里面是 0)

这个特性让条件判断非常简洁:

name = input("你的名字: ")

# Pythonic 写法
if name:
    print(f"你好, {name}!")

# 不推荐的写法
if name != "":
    print(f"你好, {name}!")

自定义类的真值

通过 __bool____len__ 方法控制:

class Bag:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)

bag = Bag([])
print(bool(bag))   # False — __len__ 返回 0
bag = Bag([1, 2])
print(bool(bag))   # True — __len__ 返回 2

2.4 字符串 str —— 不可变的 Unicode 序列

2.4.1 字符串创建与转义字符

# 四种创建方式
s1 = 'hello'
s2 = "hello"
s3 = '''多行
字符串'''
s4 = """也可以用
双引号"""

# 单引号和双引号没有区别,选择一种保持一致即可
# 字符串内含有引号时,用另一种包裹
msg = "It's a beautiful day"
html = '<div class="box">text</div>'

转义字符

print("hello\nworld")    # 换行
print("tab\there")       # 制表符
print("back\\slash")     # 反斜杠
print("quote\"inside")   # 引号

# 原始字符串 — 不处理转义
path = r"C:\Users\new_folder\test"
print(path)  # C:\Users\new_folder\test

字符串是不可变的

s = "hello"
# s[0] = "H"  # TypeError: 'str' object does not support item assignment

# 需要创建新字符串
s = "H" + s[1:]  # "Hello"

2.4.2 字符串格式化

Python 有三种格式化方式,推荐使用 f-string

name = "Alice"
age = 30
score = 95.678

# 方式 1: % 格式化(老式,不推荐)
print("Name: %s, Age: %d" % (name, age))

# 方式 2: str.format()
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {1}, Name again: {0}".format(name, age))

# 方式 3: f-string(Python 3.6+,推荐!)
print(f"Name: {name}, Age: {age}")

f-string 高级用法

# 表达式
print(f"2 + 3 = {2 + 3}")

# 格式规范
print(f"Pi = {3.14159:.2f}")      # Pi = 3.14
print(f"Score = {score:>10.1f}")   # Score =       95.7
print(f"Percent = {0.856:.1%}")    # Percent = 85.6%
print(f"Hex = {255:#x}")           # Hex = 0xff
print(f"Padded = {42:05d}")        # Padded = 00042

# 日期
from datetime import datetime
now = datetime.now()
print(f"Today: {now:%Y-%m-%d}")    # Today: 2026-03-31

# 调试神器(Python 3.8+)— 自动打印变量名和值
x = 42
print(f"{x = }")                   # x = 42
print(f"{x * 2 = }")              # x * 2 = 84

# 多行 f-string(Python 3.12+ 允许内部嵌套引号)
data = {"name": "Bob"}
print(f"Name: {data['name']}")

2.4.3 常用字符串方法

s = "  Hello, World!  "

# 大小写
s.upper()          # "  HELLO, WORLD!  "
s.lower()          # "  hello, world!  "
s.title()          # "  Hello, World!  "
s.capitalize()     # "  hello, world!  "
s.swapcase()       # "  hELLO, wORLD!  "

# 去空白
s.strip()          # "Hello, World!"
s.lstrip()         # "Hello, World!  "
s.rstrip()         # "  Hello, World!"

# 查找与替换
s.find("World")    # 9 — 返回索引,找不到返回 -1
s.index("World")   # 9 — 找不到抛出 ValueError
s.count("l")       # 3
s.replace("World", "Python")  # "  Hello, Python!  "

# 判断
"hello".startswith("he")   # True
"hello".endswith("lo")     # True
"12345".isdigit()          # True
"hello".isalpha()          # True
"hello123".isalnum()       # True

# 分割与连接
"a,b,c".split(",")        # ['a', 'b', 'c']
"hello world".split()      # ['hello', 'world'] — 默认按空白分割
",".join(["a", "b", "c"])  # "a,b,c"
"\n".join(["line1", "line2"])  # "line1\nline2"

# 对齐
"hi".center(10, "-")  # "----hi----"
"hi".ljust(10, ".")   # "hi........"
"hi".rjust(10, ".")   # "........hi"
"42".zfill(5)          # "00042"

2.4.4 字符串切片与索引

s = "Python"
#    P  y  t  h  o  n
#    0  1  2  3  4  5    正向索引
#   -6 -5 -4 -3 -2 -1   反向索引

# 索引
s[0]      # 'P'
s[-1]     # 'n'

# 切片 [start:stop:step]
s[0:3]    # 'Pyt'  — 包含 start,不包含 stop
s[:3]     # 'Pyt'  — start 省略默认 0
s[3:]     # 'hon'  — stop 省略默认到末尾
s[::2]    # 'Pto'  — 每隔一个取一个
s[::-1]   # 'nohtyP' — 反转字符串

# 切片不会越界
s[0:100]  # 'Python' — 自动截断,不报错
s[100]    # IndexError — 索引会越界!

2.5 bytes 与 bytearray

bytes 是不可变的字节序列,bytearray 是可变版本。处理二进制数据、网络通信、文件 I/O 时经常用到。

# 创建 bytes
b1 = b"hello"            # 字面量(仅限 ASCII)
b2 = bytes([72, 101])    # 从整数列表创建
b3 = "你好".encode("utf-8")  # 字符串编码为 bytes

print(b3)        # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(len(b3))   # 6 — "你好"在 UTF-8 中占 6 字节

# bytes → str
b3.decode("utf-8")  # "你好"

# bytearray — 可变
ba = bytearray(b"hello")
ba[0] = 72  # 修改第一个字节('H' 的 ASCII 码)
print(ba)   # bytearray(b'Hello') — 不对,72 就是 'H',原本也是 'h'=104
ba[0] = 72  # 'H' = 72
print(ba)   # bytearray(b'Hello')

str 与 bytes 的关系

# str  → bytes: encode
# bytes → str:  decode

text = "Python 很棒"
encoded = text.encode("utf-8")    # bytes
decoded = encoded.decode("utf-8") # str

# 常见编码:utf-8(推荐)、gbk(中文 Windows)、ascii

2.6 None 类型

None 是 Python 中表示”无”的唯一值,类型为 NoneType

x = None
print(type(x))  # <class 'NoneType'>

# 判断是否为 None 时用 is,不要用 ==
if x is None:
    print("x is None")

if x is not None:
    print("x has a value")

常见用途

# 1. 函数没有 return 时默认返回 None
def do_something():
    print("done")

result = do_something()
print(result)  # None

# 2. 用作默认参数的哨兵值
def append_to(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target

# 3. 表示可选值
class User:
    def __init__(self, name, email=None):
        self.name = name
        self.email = email  # 可能有,也可能没有

None 的特性

# None 是 falsy
bool(None)  # False

# None 是单例 — 全局只有一个 None 对象
a = None
b = None
print(a is b)  # True
print(id(a) == id(b))  # True

本章小结:Python 的基本数据类型包括数字(int/float/complex)、布尔(bool)、字符串(str)、字节(bytes/bytearray)和 None。理解浮点数精度陷阱、字符串不可变性、真值判断规则是写出正确 Python 代码的基础。