# Python 数据类型

## 学习目标
- 掌握 Python 的四种基本数据类型：整数、浮点数、字符串、布尔值
- 学会类型转换的方法
- 了解如何查看和判断变量的类型

---

![Python数据类型体系](https://img.zhaojq.top/20260730221644619.jpg "Python数据类型体系")

## 一、Python 的数据类型概览

Python 是动态类型语言，变量类型在运行时自动确定。主要的数据类型包括：

| 类型 | 英文 | 示例 | 说明 |
|------|------|------|------|
| 整数 | `int` | `100`, `-5`, `0` | 没有大小限制 |
| 浮点数 | `float` | `3.14`, `-0.5` | 双精度小数 |
| 字符串 | `str` | `"hello"`, `'world'` | 文本数据 |
| 布尔值 | `bool` | `True`, `False` | 逻辑值 |
| 空值 | `NoneType` | `None` | 表示空或无 |

---

## 二、整数（int）

```python
# 整数定义
a = 100
b = -50
c = 0

# Python 3 整数没有大小限制
big_number = 123456789012345678901234567890
print(big_number)
# 123456789012345678901234567890

# 不同进制表示
binary = 0b1010      # 二进制，值为 10
octal = 0o17         # 八进制，值为 15
hexadecimal = 0xFF   # 十六进制，值为 255

print(binary, octal, hexadecimal)
# 10 15 255
```

### 常用整数操作

```python
x = 17
y = 5

print(x + y)    # 加法: 22
print(x - y)    # 减法: 12
print(x * y)    # 乘法: 85
print(x / y)    # 除法: 3.4（返回 float）
print(x // y)   # 整除: 3
print(x % y)    # 取余: 2
print(x ** y)   # 幂运算: 1419857
print(divmod(x, y))  # (3, 2) 返回商和余数
```

---

## 三、浮点数（float）

```python
# 浮点数定义
pi = 3.14159
temperature = -10.5
scientific = 1.5e3   # 科学计数法，等于 1500.0

print(pi, temperature, scientific)
# 3.14159 -10.5 1500.0

# 浮点数精度问题
print(0.1 + 0.2)
# 0.30000000000000004

# 解决方法：使用 round() 或 Decimal
print(round(0.1 + 0.2, 2))   # 0.3

from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
print(a + b)   # 0.3（精确计算）
```

---

## 四、字符串（str）

```python
# 字符串定义（单引号、双引号、三引号均可）
s1 = 'Hello'
s2 = "World"
s3 = '''多行
字符串'''
s4 = """也支持
双引号多行"""

# 字符串拼接
full = s1 + " " + s2
print(full)   # Hello World

# 字符串重复
line = "-" * 20
print(line)   # --------------------

# 字符串长度
print(len(s1))   # 5

# 转义字符
path = "C:\\Users\\Admin"   # 使用反斜杠需要转义
path_raw = r"C:\Users\Admin"  # 原始字符串，不转义
print(path)
print(path_raw)
```

### 字符串索引与切片

```python
text = "Python"

# 索引（从 0 开始）
print(text[0])    # P
print(text[-1])   # n（最后一个字符）

# 切片 [start:end:step]
print(text[0:3])    # Pyt
print(text[:3])     # Pyt（从头开始）
print(text[3:])     # hon（到末尾）
print(text[::2])    # Pto（每隔一个字符）
print(text[::-1])   # nohtyP（反转字符串）
```

### 常用字符串方法

```python
s = "  Hello, Python!  "

print(s.strip())           # "Hello, Python!"（去空白）
print(s.lower())           # "  hello, python!  "
print(s.upper())           # "  HELLO, PYTHON!  "
print(s.replace("Python", "World"))   # "  Hello, World!  "
print(s.split(","))        # ['  Hello', ' Python!  ']
print(",".join(["a", "b", "c"]))      # a,b,c
print(s.find("Python"))    # 9（查找子串位置，-1 表示未找到）
print("Python" in s)       # True（判断是否包含）
```

---

## 五、布尔值（bool）

```python
# 布尔值只有两种
flag1 = True
flag2 = False

print(type(flag1))   # <class 'bool'>

# 比较运算产生布尔值
print(5 > 3)     # True
print(5 == 3)    # False
print(5 != 3)    # True

# 逻辑运算
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

# 布尔值在数值运算中
print(True + True)   # 2（True 等价于 1）
print(False * 10)    # 0（False 等价于 0）
```

### 真值判断

```python
# 以下值被视为 False
print(bool(0))       # False
print(bool(""))      # False
print(bool([]))      # False
print(bool(None))    # False

# 以下值被视为 True
print(bool(1))       # True
print(bool("hello")) # True
print(bool([1, 2]))  # True
```

---

## 六、空值（None）

```python
# None 表示空值或没有值
result = None
print(result)        # None
print(type(result))  # <class 'NoneType'>

# 常用于函数无返回值或变量未初始化

def do_nothing():
    pass

print(do_nothing())  # None
```

---

## 七、类型查看与转换

### 查看类型

```python
x = 100
y = 3.14
z = "hello"

print(type(x))   # <class 'int'>
print(type(y))   # <class 'float'>
print(type(z))   # <class 'str'>
```

### 类型转换

```python
# int() 转换为整数
print(int(3.9))        # 3（截断小数）
print(int("100"))      # 100
print(int("1010", 2))  # 10（二进制转十进制）

# float() 转换为浮点数
print(float(5))        # 5.0
print(float("3.14"))   # 3.14

# str() 转换为字符串
print(str(100))        # "100"
print(str(True))       # "True"
print(str([1, 2, 3]))  # "[1, 2, 3]"

# bool() 转换为布尔值
print(bool(1))         # True
print(bool(0))         # False
print(bool("hello"))   # True
print(bool(""))        # False
```

---

## 八、综合示例

```python
"""
数据类型综合练习：用户信息处理
"""

# 原始数据
user_input = "  Alice  ,  25  ,  1.68  "

# 去除空格并分割
parts = [p.strip() for p in user_input.split(",")]
name = parts[0]
age = int(parts[1])
height = float(parts[2])

print("=" * 30)
print(f"姓名: {name}")
print(f"年龄: {age} (类型: {type(age).__name__})")
print(f"身高: {height}m (类型: {type(height).__name__})")
print(f"是否成年: {age >= 18}")
print("=" * 30)

# 字符串格式化输出
info = f"{name} 今年 {age} 岁，身高 {height:.2f} 米"
print(info)
```

---

## 小结

- Python 基本类型：`int`、`float`、`str`、`bool`、`NoneType`
- 字符串支持丰富的索引、切片和方法操作
- 使用 `type()` 查看变量类型，使用 `int()`、`str()` 等函数转换类型
- 布尔值 `True` / `False` 可用于逻辑运算和条件判断
- `None` 表示空值，常用于默认值或未初始化状态

---

## 练习

1. 定义三个变量分别存储整数、浮点数、字符串，打印它们的类型。
2. 输入一个三位整数，分别输出它的百位、十位、个位数字。
3. 输入一个字符串，输出它的反转、大写形式和长度。
4. 解释为什么 `0.1 + 0.2 != 0.3`，并写出精确比较的代码。

