基本数据类型
所属模块:语法基础
难度等级:⭐️
📌 学习目标
- 掌握Python中四种基本数据类型:整数、浮点数、布尔值和字符串
- 理解每种数据类型的特点和使用场景
- 能够进行基本的数据类型转换
- 学会使用字符串的常用操作
- 避免数据类型使用中的常见错误
📘 核心内容
1. 整数(int)
整数是没有小数部分的数字,可以是正数、负数或零。Python中的整数没有大小限制(仅受限于可用内存)。
# 整数示例
positive_int = 42 # 正整数
negative_int = -7 # 负整数
zero = 0 # 零
big_int = 123456789012345678901234567890 # 大整数
# 整数类型检查
print(type(positive_int)) # 输出: <class 'int'>
# 整数运算
a = 10
b = 3
print(a + b) # 加法: 13
print(a - b) # 减法: 7
print(a * b) # 乘法: 30
print(a // b) # 整除: 3(向下取整)
print(a % b) # 取余: 1
print(a **b) # 幂运算: 1000
💡提示:Python 3中,
/
运算符返回浮点数,//
返回整数(向下取整)。对于负数整除,结果会向下取整到更小的负数,例如-10 // 3
的结果是-4
。
2. 浮点数(float)
浮点数是带有小数部分的数字,用于表示实数。
# 浮点数示例
positive_float = 3.14
negative_float = -0.001
scientific_notation = 2.5e3 # 科学计数法,等于2500.0
another_notation = 5e-2 # 等于0.05
# 浮点数类型检查
print(type(positive_float)) # 输出: <class 'float'>
# 浮点数运算
x = 2.5
y = 1.5
print(x + y) # 4.0
print(x - y) # 1.0
print(x * y) # 3.75
print(x / y) # 1.6666666666666667
浮点数的精度问题:
# 注意浮点数的精度限制
print(0.1 + 0.2) # 输出: 0.30000000000000004,而不是0.3
# 处理精度问题的方法
print(round(0.1 + 0.2, 1)) # 四舍五入到1位小数,输出: 0.3
# 或使用decimal模块进行高精度计算
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 输出: 0.3
💡提示:由于计算机表示浮点数的方式,会出现精度误差。在需要精确计算的场景(如金融领域),应使用
decimal
模块或整数运算(如以分为单位计算金额)。
3. 布尔值(bool)
布尔值用于表示真(True)或假(False),主要用于条件判断。
# 布尔值示例
is_true = True
is_false = False
# 布尔类型检查
print(type(is_true)) # 输出: <class 'bool'>
# 布尔值在条件判断中的应用
age = 18
is_adult = age >= 18
print(is_adult) # 输出: True
if is_adult:
print("已成年") # 此语句会执行
else:
print("未成年")
# 布尔运算
print(True and False) # 与运算: False
print(True or False) # 或运算: True
print(not True) # 非运算: False
其他类型转换为布尔值的规则:
# 以下值转换为bool时为False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False
print(bool(None)) # False
# 其他大多数值转换为bool时为True
print(bool(1)) # True
print(bool(-0.5)) # True
print(bool("hello")) # True
print(bool([1, 2])) # True
💡 提示:布尔值实际上是整数的子类,
True
等价于1
,False
等价于0
。因此可以参与算术运算,但不推荐这样使用,会降低代码可读性。
4. 字符串(str)
字符串是由字符组成的序列,用于表示文本信息。在Python中,字符串可以用单引号'
、双引号"
或三引号'''
/"""
包裹。
# 字符串定义
single_quoted = 'Hello, World!'
double_quoted = "Python Programming"
multi_line = '''这是一个
多行字符串
使用三单引号'''
another_multi = """这也是一个
多行字符串
使用三双引号"""
# 字符串类型检查
print(type(single_quoted)) # 输出: <class 'str'>
# 包含引号的字符串
print('He said "Hello"') # 单引号中包含双引号
print("It's a cat") # 双引号中包含单引号
print('He said \'Hello\'') # 使用转义字符
# 字符串连接与重复
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # 连接字符串
print(full_name) # 输出: John Doe
stars = "*" * 10 # 重复字符串
print(stars) # 输出: **********
字符串索引与切片:
s = "Python"
print(s[0]) # 第一个字符: 'P'
print(s[-1]) # 最后一个字符: 'n'
print(s[2:4]) # 切片: 'th'(从索引2到4,不包含4)
print(s[:3]) # 从开始到索引3: 'Pyt'
print(s[3:]) # 从索引3到结束: 'hon'
常用字符串方法:
text = "Hello, Python World!"
print(text.upper()) # 转换为大写: "HELLO, PYTHON WORLD!"
print(text.lower()) # 转换为小写: "hello, python world!"
print(text.strip()) # 去除首尾空白(本示例无空白)
print(text.split()) # 分割为列表: ['Hello,', 'Python', 'World!']
print(text.replace("Python", "Programming")) # 替换: "Hello, Programming World!"
print("Python" in text) # 检查包含: True
print(len(text)) # 长度: 20
格式化字符串:
name = "Alice"
age = 30
# f-string(Python 3.6+,推荐)
print(f"My name is {name} and I'm {age} years old.")
# format()方法
print("My name is {} and I'm {} years old.".format(name, age))
# 旧式格式化(不推荐)
print("My name is %s and I'm %d years old." % (name, age))
💡 提示:Python中的字符串是不可变的,所有字符串方法都返回新的字符串,不会修改原字符串。f-string是最简洁直观的字符串格式化方式,推荐优先使用。
5. 数据类型转换
Python提供了内置函数用于基本数据类型之间的转换:
# 转换为整数
print(int("123")) # 123
print(int(3.9)) # 3(向下取整)
print(int(True)) # 1
print(int(False)) # 0
# 转换为浮点数
print(float("3.14")) # 3.14
print(float(42)) # 42.0
print(float(True)) # 1.0
# 转换为布尔值
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("text")) # True
# 转换为字符串
print(str(123)) # "123"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
转换失败的情况:
# 以下转换会抛出ValueError
try:
int("hello") # 字符串不能转换为整数
except ValueError as e:
print(e) # 输出: invalid literal for int() with base 10: 'hello'
try:
float("12.3.4") # 无效的浮点数格式
except ValueError as e:
print(e) # 输出: could not convert string to float: '12.3.4'
💡 提示:进行类型转换时,应确保源数据可以被正确转换,必要时使用
try-except
块捕获转换错误,避免程序崩溃。
🔍 常见问题(FAQ)
Q:为什么0.1 + 0.2
不等于0.3
?
A:这是由于浮点数在计算机中的存储方式导致的精度问题。计算机使用二进制表示浮点数,有些十进制小数无法精确表示,导致微小的误差。可以使用round()
函数或decimal
模块处理这种情况。
Q:单引号和双引号在定义字符串时有什么区别?
A:在Python中,单引号和双引号没有功能上的区别,选择哪种主要取决于个人习惯和字符串内容。当字符串中包含一种引号时,使用另一种引号包裹可以避免转义。
Q:如何判断一个变量的数据类型?
A:可以使用type()
函数查看变量类型,如type(42)
返回<class 'int'>
。也可以使用isinstance()
函数检查是否为特定类型,如isinstance(42, int)
返回True
。
Q:字符串是值类型还是引用类型?
A:Python中的字符串是不可变的序列类型,属于值类型的范畴。当你修改字符串时,实际上是创建了一个新的字符串对象,而不是修改原对象。
Q:为什么"5" + 5
会报错,而"5" * 5
却可以正常工作?
A:Python不允许字符串和数字直接相加(会导致TypeError
),但允许字符串与整数相乘,表示将字符串重复指定次数。这种设计是为了方便创建重复模式的字符串。
🏁 本节总结
- ✅ Python的四种基本数据类型:整数(int)、浮点数(float)、布尔值(bool)和字符串(str)
- ✅ 整数无大小限制,浮点数可能存在精度问题,布尔值表示真/假,字符串用于文本
- ✅ 字符串支持索引、切片和多种方法操作,且是不可变的
- ✅ 可以使用
int()
、float()
、bool()
和str()
函数进行类型转换 - ✅ 理解并正确使用各种数据类型是编写Python程序的基础
- ✅ 注意处理浮点数精度问题和类型转换可能出现的错误