一、变量与数据类型
1.1 为什么学变量?
程序运行时需要临时存储数据,变量就是存放数据的"盒子",方便后续使用。
1.2 为什么学数据类型?
不同类型的数据操作方式不同,比如数字可以加减,文字可以拼接。了解类型才能正确操作。
1.3 八大基本数据类型速查表
| 类型 | 通俗理解 | 例子 |
|---|---|---|
| int | 整数(年龄、编号) | age = 18 |
| float | 小数(价格、身高) | price = 99.9 |
| str | 文字(名字、地址) | name = "dream" |
| list | 有序的一串,可增删改 | ["dream", "hope"] |
| dict | 带标签的盒子(键值对) | {"name":"dream", "age":18} |
| bool | 只有两个值:对/错 | is_student = True |
| tuple | 跟列表一样,但不能改 | (1, 2, 3) |
| set | 无序、自动去重 | {1, 2, 3} |
1.4 最常用的四种(天天见)
数字(int / float)
a = 10
b = 3.14
print(a + b) # 直接算数
字符串(str)
name = "dream"
# 三种格式化,推荐 f-string
print(f"我叫{name}")
print("我叫%s" % name)
print("我叫{}".format(name))
列表(list)
students = ["dream", "hope"]
print(students[0]) # 索引取值
students.append("opp") # 追加
字典(dict)
person = {"name": "dream", "age": 18}
print(person["name"]) # 通过键取值
print(person.get("age")) # 安全取值,找不到返回 None
1.5 布尔类型(bool)------ 只有真假
以下情况为 False ,其余全为 True:
-
False本身 -
数字
0 -
空字符串
"" -
空列表
[] -
空字典
{} -
空元组
() -
空集合
set()
特别注意:" "(空格字符串)不是空,是 True。
1.6 元组(tuple)与集合(set)
-
元组 :不能修改的列表。单元素必须加逗号
(1,),否则是整数。 -
集合:自动去重,无序,常用于去重和集合运算(并、交、差)。
二、循环与控制
2.1 range() ------ 生成数字序列(懒加载)
range(1, 6) # 1,2,3,4,5(不含6)
range(1, 9, 2) # 1,3,5,7
list(range(5)) # 转成列表 [0,1,2,3,4]
2.2 for 循环 ------ 挨个取元素
for i in "dream":
print(i)
for item in [1,2,3]:
print(item)
# 遍历字典拿到的是键
for k in {"name":"dream", "age":18}:
print(k, dict[k])
2.3 while 循环 ------ 条件满足就一直做
count = 0
while count < 5:
print(count)
count += 1 # 别忘了改条件,否则死循环
2.4 break 与 continue
-
break:立刻结束整个循环 -
continue:跳过本次,继续下一次
# continue 示例:跳过偶数
for i in range(1,6):
if i % 2 == 0:
continue
print(i) # 1,3,5
# break 示例:遇到3就停
for i in range(1,6):
if i == 3:
break
print(i) # 1,2
2.5 死循环与标志位
# 危险!别写
while True:
print("停不下来")
# 用标志位控制
flag = True
count = 0
while flag:
count += 1
if count == 5:
flag = False
2.6 while...else(了解)
循环正常结束(没被 break)时执行 else。
三、三元运算(简化 if-else)
# 普通写法
if a > b:
result = a
else:
result = b
# 三元运算
result = a if a > b else b
注意 :只适合简单判断,复杂逻辑请用 if-elif-else。
四、数据类型内置方法(常用部分)
4.1 数字(int/float)
-
int("55")转整数 -
bin(999)转二进制,oct()转八进制,hex()转十六进制 -
int("0b1111", 2)其他进制转十进制 -
"123".isdigit()判断字符串是否纯数字(常用输入校验)
4.2 字符串高频操作
| 操作 | 说明 |
|---|---|
| `" | ".join(["a","b"])` |
| `"a | b".split(" |
" dream ".strip() |
去除首尾空格或指定字符 |
"dream".replace("d","a") |
替换子串 |
"Hi".upper() / .lower() |
全大写 / 全小写 |
"dream".startswith("d") |
判断开头 |
"123".isdigit() |
是否纯数字 |
"abc".find("b") |
找索引(找不到返回 -1) |
"abc".index("b") |
找索引(找不到报错) |
"ababa".count("a") |
统计出现次数 |
"a".center(3,"*") |
居中填充(*a*) |
4.3 列表常用方法
| 操作 | 说明 |
|---|---|
lst.append(4) |
尾部添加 |
lst.insert(0,0) |
指定位置插入 |
lst.extend([5,6]) |
合并列表 |
lst.remove(0) |
删除指定值(第一个) |
lst.pop() |
弹出末尾(返回删除值) |
lst.pop(0) |
弹出指定索引 |
del lst[0] |
删除指定索引 |
lst.clear() |
清空 |
lst.sort() |
原地排序(升序) |
lst.sort(reverse=True) |
原地降序 |
sorted(lst) |
返回新排序列表 |
lst.reverse() |
原地反转 |
lst[::-1] |
切片反转(不改变原列表) |
4.4 字典常用方法
| 操作 | 说明 |
|---|---|
d["key"] |
取值(键必须存在) |
d.get("key", default) |
安全取值,可设默认值 |
d["new_key"] = value |
添加或修改 |
d.update({"b":2}) |
批量更新 |
del d["key"] |
删除键值对 |
d.pop("key") |
删除并返回值 |
d.clear() |
清空 |
for k in d: |
遍历键 |
for k,v in d.items(): |
同时遍历键和值 |
d.keys() / d.values() |
获取所有键/值 |
4.5 集合常用方法
| 操作 | 说明 |
|---|---|
s.add(4) |
添加单个元素 |
s.update([5,6,7]) |
添加多个 |
s.remove(4) |
删除(不存在报错) |
s.discard(10) |
删除(不存在不报错) |
s.pop() |
随机删除一个 |
| `a | b` |
a & b |
交集 |
a - b |
差集 |
a ^ b |
对称差集(并集减交集) |
五、可变与不可变类型(面试常问)
判断标准 :修改后内存地址(id())是否改变。
-
不可变:int, float, str, bool, tuple 修改时会创建新对象,原对象不变。
-
可变:list, dict, set 修改时内存地址不变,直接改原对象。
重要影响:函数参数传递时,可变类型会被函数内部修改影响外部。
# 不可变类型
x = 1
print(id(x)) # 地址A
x = 2
print(id(x)) # 地址B(不同)
# 可变类型
lst = [1,2]
print(id(lst)) # 地址C
lst.append(3)
print(id(lst)) # 地址C(相同)
六、垃圾回收机制(了解原理)
Python 自动回收不再使用的内存,主要靠:
-
引用计数:每个对象被引用次数为0时回收。
-
标记-清除:解决循环引用(两个对象互相指着)。
-
分代回收:对象分代,老年代扫描频率低,提升性能。
小整数池 :-5 到 256 的整数预先创建,多个变量指向同一对象。
七、深浅拷贝(复制对象)
-
浅拷贝 :只复制最外层,内层嵌套仍共享(
copy.copy()) -
深拷贝 :递归复制全部,完全独立(
copy.deepcopy())
import copy
original = [1, 2, [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[2][0] = 999
print(shallow) # [1,2,[999,4]] 受影响
print(deep) # [1,2,[3,4]] 不受影响
八、字符编码(乱码解决)
-
编码 :字符串 → 二进制(
.encode()) -
解码 :二进制 → 字符串(
.decode())
历史:ASCII → 各国标准(GBK, Shift_JIS) → Unicode → UTF-8(通用,中文3字节)
python
text = "中国"
utf8 = text.encode("utf-8")
print(utf8.decode("utf-8")) # 中国
教训 :读写文件务必指定 encoding="utf-8"。
九、文件操作(数据持久化)
9.1 打开方式
# 手动关闭
fp = open("file.txt", "r", encoding="utf-8")
data = fp.read()
fp.close()
# with 自动关闭(推荐)
with open("file.txt", "r", encoding="utf-8") as fp:
data = fp.read()
9.2 模式
-
r:只读(文件不存在报错) -
w:只写(覆盖,不存在则创建) -
a:追加(末尾写,不存在则创建) -
rb/wb:二进制模式
9.3 常用方法
fp.read() # 读全部
fp.readline() # 读一行
fp.readlines() # 读全部到列表
fp.write(str) # 写字符串
fp.writelines(list) # 写列表
fp.tell() # 当前指针位置(字节)
fp.seek(offset, whence) # 移动指针(whence:0开头,1当前,2末尾)
注意 :UTF-8 中一个汉字占3字节,seek 要小心别切到汉字中间。
十、异常处理(防止程序崩溃)
10.1 基本结构
try:
num = int(input("数字:"))
print(10/num)
except ValueError as e:
print(f"输入不是数字:{e}")
except ZeroDivisionError as e:
print(f"除零错误:{e}")
except Exception as e:
print(f"其他错误:{e}")
else:
print("没出错才执行")
finally:
print("不管怎样都执行")
10.2 主动抛出
raise ValueError("自定义错误")
assert age >= 0, "年龄不能为负"
十一、推导式(生成式)
11.1 列表推导式
[i for i in range(10) if i%2==0] # [0,2,4,6,8]
[i**2 for i in range(5)] # [0,1,4,9,16]
[s.upper() for s in "dream"] # ['D','R','E','A','M']
11.2 字典推导式
{k:v for k,v in [("a",1),("b",2)]} # {'a':1,'b':2}
{i:i**2 for i in range(5)} # {0:0,1:1,2:4,...}
11.3 集合推导式
{i%3 for i in range(10)} # {0,1,2}
11.4 生成器表达式(不是元组推导)
gen = (i for i in range(5)) # 生成器,惰性
list(gen) # 转成列表
十二、练习题及完整答案
12.1 猜年龄游戏
题目要求:
-
设定好用户年龄,用户通过输入猜测的年龄进行匹配
-
最大尝试次数:用户最多尝试猜测3次
-
最大尝试次数后:如3次后,问用户是否还想继续玩
-
如果回答Y或y,就再给3次机会,提示【还剩最后三次机会】
-
3次都猜错的话游戏结束
-
如果回答N或n,游戏结束!
-
如果格式输入错误,提示【输入格式错误,请重新输入:】
-
-
如果猜对了,游戏结束!
python
import sys
real_age = 25
chances = 3
while True:
while chances > 0:
guess = input("猜猜我的年龄:").strip()
if not guess.isdigit():
print("输入格式错误,请输入数字!")
continue
guess = int(guess)
if guess == real_age:
print("恭喜,猜对了!")
sys.exit()
else:
chances -= 1
if chances > 0:
print(f"猜错了,还剩{chances}次机会")
else:
print("三次机会用完了")
# 三次用完,询问是否继续
while True:
again = input("还想继续玩吗?(Y/N):").strip().lower()
if again == 'y':
chances = 3
print("还剩最后三次机会")
break
elif again == 'n':
print("游戏结束")
sys.exit()
else:
print("输入格式错误,请重新输入:")
12.2 登录系统(内存版)
题目要求:
-
设定好用户名和密码,用户通过输入指定的用户名和密码进行登陆
-
最大尝试次数:用户最多尝试猜测3次
-
最大尝试次数后:如3次后,问用户是否继续登陆
-
如果回答Y或y,就再给3次机会,提示【还剩最后三次机会】
-
3次都猜错的话登录结束
-
如果回答N或n,登陆结束!
-
如果格式输入错误,提示【输入格式错误,请重新输入:】
-
-
如果猜对了,登陆结束!
python
import sys
username_db = "dream"
password_db = "123456"
attempts = 3
while True:
while attempts > 0:
username = input("用户名:").strip()
password = input("密码:").strip()
if username == username_db and password == password_db:
print("登录成功!")
sys.exit()
else:
attempts -= 1
if attempts > 0:
print(f"用户名或密码错误,还剩{attempts}次机会")
else:
print("三次机会用完了")
# 询问是否继续
while True:
again = input("是否继续登录?(Y/N):").strip().lower()
if again == 'y':
attempts = 3
print("还剩最后三次机会")
break
elif again == 'n':
print("登录失败,程序结束")
sys.exit()
else:
print("输入格式错误,请重新输入:")
12.3 多用户登录注册(文件版)
题目要求:
-
用户可以注册(校验用户名是否已存在)
-
用户可以登录(校验用户名和密码)
-
用户数据持久化保存到文件(格式:username|password|role\n)
python
import os
USER_FILE = "users.txt"
def load_users():
"""从文件加载所有用户,返回字典 {username: {"password": pwd, "role": role}}"""
users = {}
if not os.path.exists(USER_FILE):
return users
with open(USER_FILE, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split("|")
if len(parts) == 3:
name, pwd, role = parts
users[name] = {"password": pwd, "role": role}
return users
def save_users(users):
"""将用户字典写回文件"""
with open(USER_FILE, "w", encoding="utf-8") as f:
for name, info in users.items():
f.write(f"{name}|{info['password']}|{info['role']}\n")
def register():
users = load_users()
username = input("请输入用户名:").strip()
if username in users:
print("用户名已存在,请直接登录")
return False
password = input("请输入密码:").strip()
# 简单角色:第一个注册的用户设为admin,其余为user
if not users:
role = "admin"
else:
role = "user"
users[username] = {"password": password, "role": role}
save_users(users)
print(f"注册成功!您的角色是:{role}")
return True
def login():
users = load_users()
username = input("用户名:").strip()
if username not in users:
print("用户名不存在,请先注册")
return False
password = input("密码:").strip()
if users[username]["password"] == password:
print(f"登录成功!欢迎 {username}({users[username]['role']})")
return True
else:
print("密码错误")
return False
def main():
while True:
print("\n===== 用户系统 =====")
print("1. 注册")
print("2. 登录")
print("3. 退出")
choice = input("请选择:").strip()
if choice == "1":
register()
elif choice == "2":
login()
elif choice == "3":
print("再见!")
break
else:
print("输入错误,请重新选择")
if __name__ == "__main__":
main()
12.4 员工管理系统
题目要求:
-
有一个数据来存储所有的员工信息(字典嵌套)
-
添加员工(需管理员权限)
-
查看员工信息(所有员工 / 按ID查询 / 按姓名查询)
-
删除员工信息(删除所有 / 删除指定ID)
-
修改员工信息(需管理员权限)
python
import sys
# 初始员工数据(其中00003为管理员)
employees = {
"00001": {"name": "张三", "age": 25, "hobby": ["reading"], "role": "user"},
"00002": {"name": "李四", "age": 30, "hobby": ["swimming"], "role": "user"},
"00003": {"name": "王五", "age": 35, "hobby": ["music"], "role": "admin"}
}
def is_admin(user_id):
"""判断指定ID的用户是否为管理员"""
emp = employees.get(user_id)
return emp and emp.get("role") == "admin"
def add_employee(admin_id):
if not is_admin(admin_id):
print("权限不足,只有管理员可以添加员工")
return
emp_id = input("请输入员工ID:").strip()
if emp_id in employees:
print("员工ID已存在")
return
name = input("姓名:").strip()
age = input("年龄:").strip()
if not age.isdigit():
print("年龄必须是数字")
return
hobby = input("爱好(用逗号分隔):").strip()
hobby_list = [h.strip() for h in hobby.split(",") if h.strip()]
employees[emp_id] = {
"name": name,
"age": int(age),
"hobby": hobby_list,
"role": "user"
}
print(f"员工 {name} 添加成功")
def show_all_employees():
if not employees:
print("暂无员工数据")
return
print("\n所有员工信息:")
for eid, info in employees.items():
print(f"ID:{eid}, 姓名:{info['name']}, 年龄:{info['age']}, 爱好:{info['hobby']}, 角色:{info['role']}")
def find_employee_by_id(eid):
info = employees.get(eid)
if info:
print(f"ID:{eid}, 姓名:{info['name']}, 年龄:{info['age']}, 爱好:{info['hobby']}, 角色:{info['role']}")
else:
print("未找到该员工")
def find_employee_by_name(name):
found = False
for eid, info in employees.items():
if info['name'] == name:
print(f"ID:{eid}, 姓名:{info['name']}, 年龄:{info['age']}, 爱好:{info['hobby']}, 角色:{info['role']}")
found = True
if not found:
print("未找到该姓名")
def delete_all_employees(admin_id):
if not is_admin(admin_id):
print("权限不足,只有管理员可以删除所有员工")
return
confirm = input("确认删除所有员工?(Y/N):").strip().lower()
if confirm == 'y':
employees.clear()
print("已清空所有员工")
else:
print("取消删除")
def delete_employee_by_id(admin_id, eid):
if not is_admin(admin_id):
print("权限不足,只有管理员可以删除员工")
return
if eid in employees:
del employees[eid]
print(f"员工 {eid} 已删除")
else:
print("员工ID不存在")
def modify_employee(admin_id):
if not is_admin(admin_id):
print("权限不足,只有管理员可以修改员工信息")
return
eid = input("请输入要修改的员工ID:").strip()
if eid not in employees:
print("员工ID不存在")
return
print("当前信息:", employees[eid])
new_name = input("新姓名(直接回车保留原值):").strip()
new_age = input("新年龄(直接回车保留原值):").strip()
new_hobby = input("新爱好(用逗号分隔,直接回车保留原值):").strip()
if new_name:
employees[eid]['name'] = new_name
if new_age and new_age.isdigit():
employees[eid]['age'] = int(new_age)
if new_hobby:
employees[eid]['hobby'] = [h.strip() for h in new_hobby.split(",") if h.strip()]
print("修改成功")
def main():
print("===== 员工管理系统 =====")
admin_id = input("请输入您的员工ID(用于权限验证):").strip()
if not is_admin(admin_id):
print("您不是管理员,只能查看和查询员工信息")
while True:
print("\n功能菜单:")
print("1. 添加员工(需管理员)")
print("2. 查看所有员工")
print("3. 按ID查询员工")
print("4. 按姓名查询员工")
print("5. 删除所有员工(需管理员)")
print("6. 删除指定员工(需管理员)")
print("7. 修改员工信息(需管理员)")
print("0. 退出")
choice = input("请选择:").strip()
if choice == "1":
add_employee(admin_id)
elif choice == "2":
show_all_employees()
elif choice == "3":
eid = input("请输入员工ID:").strip()
find_employee_by_id(eid)
elif choice == "4":
name = input("请输入姓名:").strip()
find_employee_by_name(name)
elif choice == "5":
delete_all_employees(admin_id)
elif choice == "6":
eid = input("请输入要删除的员工ID:").strip()
delete_employee_by_id(admin_id, eid)
elif choice == "7":
modify_employee(admin_id)
elif choice == "0":
print("退出系统")
break
else:
print("输入有误,请重新选择")
if __name__ == "__main__":
main()