目录
[1.1 字面量(Literal)](#1.1 字面量(Literal))
[1.2 变量(Variable)](#1.2 变量(Variable))
[1.3 标识符命名规则](#1.3 标识符命名规则)
[1.4 变量交换(Python 独门绝技)](#1.4 变量交换(Python 独门绝技))
[2.1 基本类型一览](#2.1 基本类型一览)
[2.2 类型检查与转换](#2.2 类型检查与转换)
[2.3 字符串操作](#2.3 字符串操作)
[2.4 输入输出](#2.4 输入输出)
[3.1 运算符家族](#3.1 运算符家族)
[3.2 运算符实战](#3.2 运算符实战)
[3.3 综合练习](#3.3 综合练习)
[四、流程控制 ------ 让程序"有脑子"](#四、流程控制 —— 让程序"有脑子")
[4.1 条件判断](#4.1 条件判断)
[4.2 模式匹配(Python 3.10+)](#4.2 模式匹配(Python 3.10+))
[4.3 循环](#4.3 循环)
[4.4 嵌套循环与九九乘法表](#4.4 嵌套循环与九九乘法表)
[4.5 break 与 continue](#4.5 break 与 continue)
[五、数据容器 ------ 存放数据的"盒子"](#五、数据容器 —— 存放数据的"盒子")
[5.1 容器对比总览](#5.1 容器对比总览)
[5.2 列表(List)------ 最常用的容器](#5.2 列表(List)—— 最常用的容器)
[5.3 字典(Dict)------ 键值对存储](#5.3 字典(Dict)—— 键值对存储)
[5.4 集合(Set)------ 自动去重](#5.4 集合(Set)—— 自动去重)
[5.5 元组(Tuple)------ 不可修改的列表](#5.5 元组(Tuple)—— 不可修改的列表)
变量是数据的容器,容器是变量的集合------搞懂这三者,你就掌握了 Python 的骨架。
一、字面量与变量
1.1 字面量(Literal)
字面量就是程序中直接书写的固定值:
python
18 # 整数字面量
3.1415 # 浮点数字面量
"Hello World" # 字符串字面量
True # 布尔字面量
None # 空值字面量
1.2 变量(Variable)
变量是程序中存储数据的容器,数据会变,容器不变:
python
# 定义格式:变量名 = 值
play_count = 20.7 # 当前播放量
# 数据变化,变量可以重新赋值
play_count = play_count + 50 # 新增50万播放
print(f"播放量:{play_count} 万") # 70.7 万
play_count = play_count + 50
print(f"播放量:{play_count} 万") # 120.7 万
1.3 标识符命名规则
python
# ✅ 规范命名
user_name = "张三"
total_price = 99.99
max_retry_count = 3
# ❌ 不规范
a = "张三" # 不知道 a 代表什么
username = "张三" # 没有用下划线分隔
6name = "张三" # 数字不能开头(会直接报错)
and = "张三" # 关键字不能用作变量名
1.4 变量交换(Python 独门绝技)
python
# 经典方式(其他语言)
a, b = 10, 20
temp = a
a = b
b = temp
# Python 方式 ------ 一行搞定!
a, b = b, a
print(a, b) # 20 10
# 三个变量交换也不在话下
a, b, c = 100, 200, 300
a, b, c = b, c, a # a=200, b=300, c=100
二、数据类型
2.1 基本类型一览
| 类型 | 关键字 | 示例 | 说明 |
|---|---|---|---|
| 整数 | int |
18, -5 |
无小数点 |
| 浮点数 | float |
3.14, -0.5 |
带小数点 |
| 字符串 | str |
"Python" |
三种引号均可 |
| 布尔 | bool |
True, False |
首字母大写 |
| 空值 | NoneType |
None |
表示"什么都没有" |
2.2 类型检查与转换
python
# 查看类型
print(type(18)) # <class 'int'>
print(type("Hello")) # <class 'str'>
# 类型检查
print(isinstance(18, int)) # True
print(isinstance("18", int)) # False
# 类型转换
num_str = "123"
num = int(num_str) # str → int
price = float("99.99") # str → float
text = str(999) # int → str
flag = bool(1) # int → bool (非0即True)
2.3 字符串操作
python
# 三种定义方式
s1 = 'Hello' # 单引号
s2 = "Python" # 双引号(等效)
s3 = """多行
字符串""" # 三引号
# 转义字符
print("It's a good day") # 内外引号不同,无需转义
print('It\'s a good day') # 转义单引号
print("第一行\n第二行") # \n 换行
print("姓名\t年龄\t城市") # \t 制表符
# 字符串格式化 ------ 推荐 f-string
name = "小李"
age = 25
hobby = "Python"
print(f"大家好,我是{name},今年{age}岁,热爱{hobby}")
# 传统 % 格式化(了解即可)
print("大家好,我是%s,今年%d岁" % (name, age))
2.4 输入输出
python
# input() ------ 获取用户输入(返回的始终是字符串!)
name = input("请输入您的姓名:")
age_str = input("请输入您的年龄:")
age = int(age_str) # 转为整数才能计算
# print() ------ 输出到控制台
print("Hello", "World", sep="-") # Hello-World
print("Loading", end="...") # 不换行
实战:ATM 取款机模拟
python
balance = 10000.00
password = input("请输入密码:")
if password == "123456":
amount = float(input("请输入取款金额:"))
if amount <= balance:
balance -= amount
print(f"取款成功!余额:{balance:.2f} 元")
else:
print("余额不足!")
else:
print("密码错误!")
三、运算符
3.1 运算符家族
3.2 运算符实战
python
# 算术运算
print(10 / 3) # 3.3333333333333335 普通除法
print(10 // 3) # 3 整除(去尾)
print(10 % 3) # 1 取余
print(2 ** 10) # 1024 2的10次方
# ⚠️ 浮点数精度陷阱
print(0.1 + 0.2) # 0.30000000000000004(不是0.3!)
# 原因:计算机用二进制无法精确表示所有小数
# 比较运算 ------ 判断偶数
num = 42
print(num % 2 == 0) # True
# 逻辑运算 ------ 登录验证
username = "admin"
password = "666888"
input_user = input("用户名:")
input_pwd = input("密码:")
if input_user == username and input_pwd == password:
print("登录成功!")
else:
print("用户名或密码错误")
3.3 综合练习
python
import math
# 案例 1:计算梯形面积
top = float(input("上底:"))
bottom = float(input("下底:"))
height = float(input("高:"))
area = (top + bottom) * height / 2
print(f"梯形面积:{area:.2f}")
# 案例 2:计算圆的周长和面积
r = float(input("半径:"))
circumference = 2 * math.pi * r
area = math.pi * r ** 2
print(f"周长:{circumference:.2f},面积:{area:.2f}")
# 案例 3:BMI 指数
weight = float(input("体重(kg):"))
height_m = float(input("身高(m):"))
bmi = weight / height_m ** 2
print(f"BMI 指数:{bmi:.1f}")
四、流程控制 ------ 让程序"有脑子"
4.1 条件判断
python
# if...elif...else 多分支判断
score = int(input("请输入成绩:"))
if score >= 85:
grade = "优秀"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
print(f"成绩等级:{grade}")
实战:阶梯电价计算
python
degree = float(input("用电度数:"))
if degree <= 2880:
fee = degree * 0.4883
elif degree <= 4800:
fee = 2880 * 0.4883 + (degree - 2880) * 0.5383
else:
fee = 2880 * 0.4883 + 1920 * 0.5383 + (degree - 4800) * 0.7883
print(f"电费:{fee:.2f} 元")
4.2 模式匹配(Python 3.10+)
python
# match...case ------ 多固定值匹配更清晰
operator = input("输入运算符(+-*/):")
a, b = 10, 5
match operator:
case "+":
print(f"{a}+{b}={a+b}")
case "-":
print(f"{a}-{b}={a-b}")
case "*":
print(f"{a}×{b}={a*b}")
case "/":
print(f"{a}÷{b}={a/b}")
case _:
print("不支持的运算符")
4.3 循环
python
# while 循环 ------ 不知道具体次数
count = 0
while count < 5:
print(f"第 {count+1} 次:人生苦短,我用 Python")
count += 1
# for 循环 ------ 遍历已知数据集
for ch in "Python":
print(ch, end=" ")
# 输出:P y t h o n
# range() ------ 生成数字序列
# range(end) 0 到 end-1
# range(start, end) start 到 end-1
# range(start, end, step) 带步长
# 计算 1-100 偶数之和
total = 0
for i in range(2, 101, 2):
total += i
print(f"1-100 偶数之和:{total}") # 2550
实战:猜数字游戏
python
import random
target = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("猜一个 1-100 的数字:"))
attempts += 1
if guess > target:
print("猜大了!")
elif guess < target:
print("猜小了!")
else:
print(f"恭喜!猜对了,用了 {attempts} 次")
break
4.4 嵌套循环与九九乘法表
python
# 经典:九九乘法表
for i in range(1, 10): # 外层:行
for j in range(1, i + 1): # 内层:列
print(f"{j}×{i}={i*j:2}", end=" ")
print() # 换行
# 输出效果:
# 1×1= 1
# 1×2= 2 2×2= 4
# 1×3= 3 2×3= 6 3×3= 9
# ...
4.5 break 与 continue
python
# break:直接跳出循环
for i in range(10):
if i == 5:
break # 遇到5就停
print(i, end=" ") # 0 1 2 3 4
# continue:跳过本次,继续下一次
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i, end=" ") # 1 3 5 7 9
五、数据容器 ------ 存放数据的"盒子"
5.1 容器对比总览
5.2 列表(List)------ 最常用的容器
python
# 定义与索引
scores = [85, 92, 78, 90, 88]
# 正向索引 0 1 2 3 4
# 反向索引 -5 -4 -3 -2 -1
print(scores[0]) # 85
print(scores[-1]) # 88
# 切片:s[start:end:step]
print(scores[1:4]) # [92, 78, 90]
print(scores[::2]) # [85, 78, 88] 隔一个取一个
print(scores[::-1]) # [88, 90, 78, 92, 85] 反转
# 常用方法
scores.append(95) # 追加
scores.insert(2, 100) # 指定位置插入
scores.remove(78) # 删除指定元素
scores.sort(reverse=True) # 降序排列
# 列表推导式 ------ Python 的精髓
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 带条件的列表推导式
even_squares = [x**2 for x in range(1, 21) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
5.3 字典(Dict)------ 键值对存储
python
# 场景:存储学生成绩
scores = {
"王林": 670,
"韩立": 556,
"李慕婉": 582,
"紫灵": 435,
"许立国": 608
}
# 增删改查
scores["南宫婉"] = 645 # 新增
scores["紫灵"] = 450 # 修改
del scores["许立国"] # 删除
print(scores["王林"]) # 查询:670
print(scores.get("张三", 0)) # 安全查询:不存在返回0
# 遍历
for name, score in scores.items():
print(f"{name}: {score} 分")
实战:购物车管理系统
python
cart = {} # {商品名: {"price": 价格, "qty": 数量}}
while True:
print("\n===== 购物车管理系统 =====")
print("1. 添加 2. 修改 3. 删除 4. 查看 5. 退出")
choice = input("请选择:")
if choice == "1":
name = input("商品名:")
price = float(input("价格:"))
qty = int(input("数量:"))
cart[name] = {"price": price, "qty": qty}
print(f"已添加 {name}")
elif choice == "2":
name = input("要修改的商品名:")
if name in cart:
cart[name]["price"] = float(input("新价格:"))
cart[name]["qty"] = int(input("新数量:"))
print(f"已修改 {name}")
else:
print("商品不存在")
elif choice == "3":
name = input("要删除的商品名:")
if cart.pop(name, None):
print(f"已删除 {name}")
else:
print("商品不存在")
elif choice == "4":
for name, info in cart.items():
print(f"{name}: 单价{info['price']}元, 数量{info['qty']}")
elif choice == "5":
print("再见!")
break
5.4 集合(Set)------ 自动去重
python
# 集合非常适合去重和交并差运算
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a & b) # 交集:{4, 5}
print(a | b) # 并集:{1, 2, 3, 4, 5, 6, 7, 8}
print(a - b) # 差集:{1, 2, 3}
# 实战:找出同时选修两门课的学生
python_students = {"张三", "李四", "王五", "赵六"}
ai_students = {"李四", "赵六", "孙七", "周八"}
both = python_students & ai_students
print(f"两门都选的:{both}") # {'李四', '赵六'}
5.5 元组(Tuple)------ 不可修改的列表
python
# 元组 = 只读列表
point = (3, 5)
rgb = (255, 128, 0)
print(point[0]) # 3
# point[0] = 10 # ❌ 报错!元组不能修改
# 单元素元组注意加逗号
single = ("A",) # ✅ 这才是元组
not_tuple = ("A") # ❌ 这只是字符串
# 组包与解包
a, b = 10, 20 # 元组组包再解包
a, b = b, a # 交换(本质就是解包)
print(a, b) # 20 10
# * 收集剩余元素
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
六、综合案例:教务管理系统
python
students = {} # {姓名: {"语文": x, "数学": y, "英语": z}}
while True:
print("\n====== 教务管理系统 ======")
print("1.添加 2.修改 3.删除 4.查询 5.列表 6.统计 7.退出")
op = input("请选择:")
if op == "1":
name = input("姓名:")
students[name] = {
"语文": int(input("语文:")),
"数学": int(input("数学:")),
"英语": int(input("英语:"))
}
elif op == "2":
name = input("姓名:")
if name in students:
students[name] = {
"语文": int(input("语文:")),
"数学": int(input("数学:")),
"英语": int(input("英语:"))
}
elif op == "3":
students.pop(input("姓名:"), None)
elif op == "4":
name = input("姓名:")
if name in students:
s = students[name]
print(f"{name}: 语文{s['语文']}, 数学{s['数学']}, 英语{s['英语']}")
elif op == "5":
for name, s in students.items():
total = sum(s.values())
print(f"{name}: 总分{total}")
elif op == "6":
for subject in ["语文", "数学", "英语"]:
scores = [s[subject] for s in students.values()]
print(f"{subject}: 最高{max(scores)}, 最低{min(scores)}, 平均{sum(scores)/len(scores):.1f}")
elif op == "7":
break
七、小结
💡 核心心法:变量存单个,容器存多个。列表最通用,字典最强大。循环处理重复,条件实现分支。这些就是你编程的"基本功"------基本功扎实了,后面学什么都快。