第 13 课 · 阶段二 · 基础语法
类型转换
类型转换是数据流通的桥梁。这一课掌握 int()、float()、str() 三大转换,理解自动转换与强制转换,并避开常见陷阱。
🎯 学完本课你将掌握
- 掌握 int、float、str 三种强制转换
- 理解 bool 转换的规则
- 识别常见的转换陷阱并正确规避
一、为什么需要类型转换
不同数据类型有时不能直接配合:字符串不能和数字相加、input 拿到的是字符串。此时就需要把一种类型转成另一种。
二、三大转换函数
| 函数 | 作用 | 示例 | 结果 |
|---|---|---|---|
| int(x) | 转整数(去小数) | int(3.99) | 3 |
| float(x) | 转浮点数 | float("3.5") | 3.5 |
| str(x) | 转字符串 | str(123) | "123" |
基础转换.py
1print(int("42")) # 42 字符串数字→整数2print(int(3.99)) # 3 浮点直接截断,不是四舍五入3print(float("2.5")) # 2.54print(str(100)) # '100'5print("数字" + str(100)) # 数字100 拼接必须转字符串三、注意 int() 的陷阱
int 陷阱.py
1print(int("3.14")) # 报错!字符串里带小数点不能直接转int2print(float("3.14")) # 3.14 先转float可以3# 正确姿势:先 float 再 int4print(int(float("3.14"))) # 3⚠️ 注意
int("3.14") 会报 ValueError,因为 int 期望字符串里是“纯整数”。带小数的字符串要先转 float。
四、bool 转换与假值
bool(x) 转换规则:0、0.0、空字符串 ""、空列表 [] 等“空值”转成 False,其余都转成 True。
bool 转换.py
1print(bool(0)) # False2print(bool(1)) # True3print(bool("")) # False 空字符串4print(bool("abc")) # True5print(bool([])) # False 空列表6print(bool([0])) # True 列表里有元素五、自动类型转换
Python 在 int 和 float 混合运算时会自动转成 float;但字符串不会自动转数字。
自动转换.py
1print(3 + 4.5) # 7.5 int自动转成float2print(True + 1) # 2 True当作13print(type(3 / 2)) # <class 'float'> 除法结果永远是float六、常见错误与解决
常见错误与解决
| 错误现象 | 原因 / 解决方法 |
|---|---|
ValueError: invalid literal for int() | int() 收到非数字字符串,检查输入是否纯数字。 |
TypeError: can only concatenate str | 字符串和数字混拼,用 str() 包住数字或用 f-string。 |
int() 转换丢掉小数 | int(3.9)=3 是截断不是四舍五入;想四舍五入用 round(3.9) → 4。 |
✍️ 小练习
输入两个带小数的数字字符串,转换成 float 求和并保留 2 位小数输出;再验证 bool("0") 是 True 还是 False 并解释原因。
📌 本节小结
int()/float()/str() 三大转换 + bool 的“空为假”规则,配合自动转换,数据就能自由流通。注意带小数点的字符串要两步转。