欢迎来到今天的 Python 基础教程!今天我们来深入讲解 Python 变量与数据类型。这是 Python 编程的基石,掌握它们对后续学习至关重要。
一、Python 变量基础
1.1 变量的定义
Python 变量不需要声明类型。直接赋值即可。Python 是动态类型语言。变量的类型在运行时确定:
# 变量定义 - 无需声明类型
name = "Python" # 字符串
version = 3.12 # 浮点数
is_awesome = True # 布尔值
count = 100 # 整数
# 查看变量类型
print(type(name)) # <class 'str'>
print(type(version)) # <class 'float'>
print(type(count)) # <class 'int'>
# 变量可以重新赋值为不同类型
count = "一百" # 现在变成字符串了
print(type(count)) # <class 'str'>
1.2 命名规则
遵循良好的命名规范可以让代码更易读:
- 基本规则:只能包含字母、数字、下划线
- 不能以数字开头:如 1name 是非法的
- 区分大小写:Name 和 name 是不同的变量
- 不能使用 Python 关键字:如 if、for、while 等
- 推荐使用小写字母和下划线:如 user_name、total_count
# 合法的变量名
user_name = "张三"
age = 25
_total = 100
# 非法的变量名(会报错)
# 1name = "李四" # 不能以数字开头
# class = "Python" # 不能使用关键字
# my-name = "王五" # 不能包含连字符
# 查看 Python 关键字
import keyword
print(keyword.kwlist) # 打印所有关键字
二、基本数据类型
2.1 数值类型
Python 支持多种数值类型。包括整数、浮点数和复数:
# 整数(int)- 任意精度
age = 25
population = 1400000000 # 14 亿
big_num = 10 ** 100 # 1 后面 100 个零。Python 能处理
# 浮点数(float)- 带小数点
price = 99.99
pi = 3.141592653589793
scientific = 1.23e-4 # 科学计数法。等于 0.000123
# 复数(complex)- 用于科学计算
complex_num = 3 + 4j
print(complex_num.real) # 3.0(实部)
print(complex_num.imag) # 4.0(虚部)
# 数值运算
a = 10
b = 3
print(a + b) # 13(加法)
print(a - b) # 7(减法)
print(a * b) # 30(乘法)
print(a / b) # 3.333...(除法。结果总是浮点数)
print(a // b) # 3(整除。只取整数部分)
print(a % b) # 1(取余)
print(a ** b) # 1000(幂运算。10 的 3 次方)
2.2 字符串类型
字符串是 Python 中最常用的数据类型之一:
# 字符串定义 - 可以用单引号或双引号
text1 = 'Hello'
text2 = "World"
# 多行字符串(使用三引号)
multiline = '''第一行
第二行
第三行'''
# 字符串拼接
greeting = "Hello" + " " + "Python"
print(greeting) # Hello Python
# 字符串重复
line = "-" * 50
print(line) # --------------------------------------------------
# 字符串索引和切片
text = "Python"
print(text[0]) # 'P'(第一个字符)
print(text[-1]) # 'n'(最后一个字符)
print(text[0:3]) # 'Pyt'(切片。不包含结束位置)
print(text[:3]) # 'Pyt'(省略开始位置)
print(text[3:]) # 'hon'(省略结束位置)
# 常用字符串方法
name = " Python "
print(name.strip()) # 'Python'(去除两端空格)
print(name.upper()) # ' PYTHON '(转大写)
print(name.lower()) # ' python '(转小写)
print(len(name)) # 10(字符串长度)
# 字符串格式化
name = "张三"
age = 25
# f-string(Python 3.6+ 推荐)
print(f"我叫{name}。今年{age}岁")
# format 方法
print("我叫{}。今年{}岁".format(name, age))
2.3 布尔类型
# 布尔值 - 只有 True 和 False
is_valid = True
is_error = False
# 布尔运算
print(True and False) # False(与)
print(True or False) # True(或)
print(not True) # False(非)
# 比较运算返回布尔值
print(5 > 3) # True
print(5 == 5) # True
print(5 != 3) # True
# 真值测试 - 以下值为 False
print(bool(0)) # False
print(bool("")) # False
print(bool(None)) # False
print(bool([])) # False
print(bool({})) # False
# 其他值都为 True
print(bool(1)) # True
print(bool("a")) # True
print(bool([1])) # True
三、容器数据类型
3.1 列表(List)
列表是最常用的容器类型。可以存储有序的元素集合:
# 列表定义
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True] # 可以包含不同类型
# 访问元素
print(fruits[0]) # '苹果'
print(fruits[-1]) # '橙子'(最后一个)
# 修改元素
fruits[1] = "葡萄"
print(fruits) # ['苹果', '葡萄', '橙子']
# 添加元素
fruits.append("西瓜") # 末尾添加
fruits.insert(1, "香蕉") # 指定位置插入
fruits.extend(["梨", "桃"]) # 扩展列表
# 删除元素
fruits.remove("苹果") # 删除指定值
del fruits[0] # 删除指定位置
last = fruits.pop() # 弹出最后一个元素
# 列表切片
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[::2]) # [0, 2, 4](步长为 2)
# 列表推导式(强大功能)
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 常用列表方法
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(nums)) # 8(长度)
print(max(nums)) # 9(最大值)
print(min(nums)) # 1(最小值)
print(sum(nums)) # 31(求和)
nums.sort() # 排序
print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
print(nums.count(1)) # 2(计数)
3.2 元组(Tuple)
元组是不可变的列表。适合存储不应改变的数据:
# 元组定义
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # 单元素元组需要逗号
# 访问元素(和列表一样)
print(coordinates[0]) # 10
print(colors[-1]) # 'blue'
# 元组解包
x, y = coordinates
print(x, y) # 10 20
# 交换变量值
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# 元组不可变(尝试修改会报错)
# coordinates[0] = 100 # TypeError!
# 元组的应用场景
# 1. 函数返回多个值
def get_user():
return ("张三", 25, "北京")
name, age, city = get_user()
# 2. 字典的键(元组可哈希)
location = {(39.9, 116.4): "北京"}
# 3. 保护数据不被修改
RGB_RED = (255, 0, 0)
3.3 字典(Dictionary)
字典是键值对的集合。用于存储映射关系:
# 字典定义
person = {
"name": "张三",
"age": 25,
"city": "北京",
"skills": ["Python", "Java", "Linux"]
}
# 访问值
print(person["name"]) # '张三'
print(person.get("age")) # 25
print(person.get("email")) # None(键不存在不报错)
print(person.get("email", "未提供")) # '未提供'(默认值)
# 添加/修改键值对
person["email"] = "zhangsan@example.com" # 添加
person["age"] = 26 # 修改
# 删除键值对
del person["city"]
age = person.pop("age") # 弹出并返回值
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
# 常用操作
print("name" in person) # True(检查键是否存在)
print(person.keys()) # 所有键
print(person.values()) # 所有值
print(len(person)) # 字典大小
# 字典推导式
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 实际应用 - 统计词频
text = "python is great python is fun"
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq) # {'python': 2, 'is': 2, 'great': 1, 'fun': 1}
3.4 集合(Set)
集合是无序且不重复的元素集合:
# 集合定义
unique_nums = {1, 2, 3, 3, 4}
print(unique_nums) # {1, 2, 3, 4}(自动去重)
# 创建空集合(注意:{}是空字典)
empty_set = set()
# 从列表创建集合(去重)
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique) # {1, 2, 3}
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1, 2, 3, 4, 5, 6}(并集)
print(a & b) # {3, 4}(交集)
print(a - b) # {1, 2}(差集)
print(a ^ b) # {1, 2, 5, 6}(对称差集)
# 集合方法
a.add(5) # 添加元素
a.remove(1) # 删除元素(不存在会报错)
a.discard(10) # 删除元素(不存在不报错)
print(3 in a) # True(成员检查)
四、类型转换
# 显式类型转换
num_str = "123"
num_int = int(num_str) # 字符串转整数:123
num_float = float("3.14") # 字符串转浮点:3.14
num_str = str(456) # 整数转字符串:"456"
# 列表、元组、集合互转
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # 列表转元组
my_set = set(my_list) # 列表转集合
# 实际应用
# 1. 用户输入处理
age_str = input("请输入年龄:")
age = int(age_str) # 转整数进行计算
# 2. 数据去重
ids = [1, 2, 2, 3, 3, 3]
unique_ids = list(set(ids)) # [1, 2, 3]
# 3. 数字格式化
price = 99.99
print(f"价格:{int(price)}元") # 价格:99 元
五、实战示例
5.1 学生信息管理系统
# 使用字典和列表管理学生信息
students = [
{"name": "张三", "age": 20, "score": 85},
{"name": "李四", "age": 21, "score": 92},
{"name": "王五", "age": 19, "score": 78}
]
# 添加学生
new_student = {"name": "赵六", "age": 20, "score": 88}
students.append(new_student)
# 计算平均分
total = sum(s["score"] for s in students)
average = total / len(students)
print(f"平均分:{average:.2f}")
# 找出最高分
best_student = max(students, key=lambda s: s["score"])
print(f"最高分:{best_student['name']} - {best_student['score']}")
# 筛选及格学生
passed = [s for s in students if s["score"] >= 60]
print(f"及格人数:{len(passed)}")
5.2 购物车程序
# 购物车数据结构
cart = {
"items": [
{"name": "iPhone 15", "price": 7999, "quantity": 1},
{"name": "AirPods", "price": 1299, "quantity": 2}
],
"discount": 0.9 # 9 折优惠
}
# 计算总价
total = 0
for item in cart["items"]:
item_total = item["price"] * item["quantity"]
total += item_total
# 应用折扣
final_price = total * cart["discount"]
print(f"原价:{total}元")
print(f"折后价:{final_price:.2f}元")
# 添加商品
cart["items"].append({"name": "充电器", "price": 149, "quantity": 1})
六、常见错误与解决
6.1 类型错误
# 错误:字符串和整数不能直接相加
# result = "年龄:" + 25 # TypeError
# 正确做法
result = "年龄:" + str(25)
result = f"年龄:{25}" # 推荐
6.2 索引越界
fruits = ["苹果", "香蕉", "橙子"]
# print(fruits[5]) # IndexError!
# 安全访问
if len(fruits) > 5:
print(fruits[5])
# 或使用切片(不会报错)
print(fruits[5:6]) # []
6.3 键不存在
person = {"name": "张三"}
# print(person["age"]) # KeyError!
# 安全访问
print(person.get("age")) # None
print(person.get("age", 0)) # 0(默认值)
七、最佳实践
- 使用有意义的变量名:user_name 比 un 更好
- 遵循命名规范:变量用小写 + 下划线
- 选择合适的数据类型:不变数据用元组。需要去重用集合
- 使用类型提示(Python 3.5+):
def greet(name: str) -> str: return f"Hello, {name}" - 善用列表推导式:简洁但不要太复杂
八、总结与练习
今天我们学习了 Python 变量和数据类型的核心知识。建议:
- 理解不同数据类型的特点:何时用列表、元组、字典、集合
- 掌握容器的使用方法:增删改查、遍历、推导式
- 熟练进行类型转换:int()、str()、float()、list() 等
- 多写代码巩固知识:实践是最好的老师
课后练习
- 创建一个包含 5 个学生信息的列表。每个学生有姓名、年龄、成绩
- 计算平均分、最高分、最低分
- 筛选出成绩大于 80 的学生
- 将学生按成绩排序
关注我们获取更多 Python 教程!下节课我们将学习 Python 运算符与表达式。
