目录
欢迎在评论区进行打卡留言,并分享学习经验,题目讲解以及分享更多内容,关注博主或者订阅专栏,可以第一时间看到博主发表的博文
字典(dict)详解
什么是字典?
字典是Python中非常重要的一种数据结构,它采用键值对(key-value)的形式来存储数据。字典在其他编程语言中也被称为映射(map)、哈希表(hash table)或关联数组。
字典的核心思想是通过键来快速查找对应的值,这种查找速度非常快,几乎不受字典大小的影响。这是因为字典内部使用了哈希表的数据结构,通过计算键的哈希值来直接定位存储位置。
字典的基本特性
字典使用大括号{}
来创建,每个键值对用冒号:
分隔,不同的键值对用逗号,
分隔。键和值可以是任意类型,但键必须是不可变类型。
**为什么键必须是不可变类型?**这是因为字典通过哈希表实现,哈希表要求键的值不能改变,否则哈希值会改变,导致无法正确找到对应的值。因此,字符串、数字、元组等不可变类型可以作为键,而列表、字典等可变类型不能作为键。
字典的创建方式
字典有多种创建方式,每种方式都有其适用场景:
python
# 方法1:直接使用大括号
person = {'name': '张三', 'age': 25, 'city': '北京'}
# 方法2:使用dict()构造函数
person = dict(name='张三', age=25, city='北京')
# 方法3:从键值对序列创建
person = dict([('name', '张三'), ('age', 25), ('city', '北京')])
# 方法4:使用字典推导式
keys = ['name', 'age', 'city']
values = ['张三', 25, '北京']
person = {k: v for k, v in zip(keys, values)}
字典的访问操作
访问字典元素有多种方法,每种方法都有不同的特性和适用场景:
python
student = {'name': '李四', 'age': 20, 'score': 95}
# 方法1:使用方括号[]访问(如果键不存在会报KeyError)
print(student['name']) # 李四
# 方法2:使用get()方法访问(键不存在时返回None或默认值)
print(student.get('age')) # 20
print(student.get('height')) # None
print(student.get('height', 180)) # 180(返回默认值)
# 方法3:使用setdefault()方法
# 如果键存在则返回对应的值,如果键不存在则设置默认值并返回
height = student.setdefault('height', 175)
print(height) # 175
print(student) # {'name': '李四', 'age': 20, 'score': 95, 'height': 175}
字典的修改和更新
字典是可变数据类型,可以随时添加、修改和删除元素:
python
# 添加新键值对
student['gender'] = '男'
print(student) # 包含gender键值对
# 修改已有键的值
student['age'] = 21
print(student['age']) # 21
# 使用update()方法批量更新
new_info = {'age': 22, 'major': '计算机科学', 'score': 98}
student.update(new_info)
print(student) # 更新了age、score,添加了major
字典的删除操作
删除字典元素也有多种方法,需要根据具体需求选择:
python
# 方法1:使用del语句删除指定键
del student['gender']
print(student) # gender键值对被删除
# 方法2:使用pop()方法删除并返回值
age = student.pop('age')
print(f"删除的年龄: {age}")
print(student) # age键值对被删除
# 方法3:使用popitem()方法删除最后一个键值对
last_item = student.popitem()
print(f"删除的键值对: {last_item}")
print(student) # 最后一个键值对被删除
# 方法4:使用clear()方法清空字典
student.clear()
print(student) # 空字典{}
字典的遍历操作
遍历字典时,可以根据需要选择遍历键、值或键值对:
python
student = {'name': '王五', 'age': 19, 'score': 88, 'major': '数学'}
# 遍历所有键
print("所有键:")
# 这里for循环还没有讲解,可以先过了,把下面的for循环看完再回头看
for key in student.keys():
print(key)
# 遍历所有值
print("\n所有值:")
for value in student.values():
print(value)
# 遍历所有键值对
print("\n所有键值对:")
for key, value in student.items():
print(f"{key}: {value}")
# 直接遍历字典(默认遍历键)
print("\n直接遍历(键):")
for key in student:
print(key)
字典的常用方法总结
字典提供了丰富的方法来操作数据:
-
keys()
: 返回所有键的视图 -
values()
: 返回所有值的视图 -
items()
: 返回所有键值对的视图 -
get(key, default)
: 安全获取值 -
setdefault(key, default)
: 获取值,不存在时设置默认值 -
update(other_dict)
: 批量更新 -
pop(key)
: 删除指定键并返回值 -
popitem()
: 删除最后一个键值对 -
clear()
: 清空字典 -
copy()
: 浅拷贝字典
字典的应用场景
字典在实际编程中有广泛的应用:
-
配置信息存储: 存储程序的配置参数
-
数据缓存: 缓存计算结果,提高程序性能
-
计数统计: 统计元素出现次数
-
数据分组: 按某个属性对数据进行分组
-
对象表示: 表示复杂对象的属性
集合(set)详解
什么是集合?
集合是Python中的另一种重要数据结构,它是一个无序的、不重复元素的序列。集合的主要用途是进行成员关系测试和消除重复元素。
集合的核心特性是:
-
无序性:元素没有固定的顺序
-
唯一性:不允许重复元素
-
可变性:可以添加和删除元素(但元素本身必须是不可变的)
集合的创建方式
集合可以通过多种方式创建:
python
# 方法1:使用大括号(注意:空集合不能用{},要用set())
fruits = {'apple', 'banana', 'orange'}
print(fruits)
# 方法2:使用set()构造函数
numbers = set([1, 2, 3, 2, 1]) # 自动去重
print(numbers) # {1, 2, 3}
# 方法3:使用集合推导式
squares = {x**2 for x in range(5)}
print(squares) # {0, 1, 4, 9, 16}
# 方法4:创建空集合
empty_set = set()
print(empty_set) # set()
集合的基本操作
集合支持丰富的操作来管理元素:
python
# 创建测试集合
colors = {'red', 'green', 'blue'}
# 添加元素
colors.add('yellow')
print(colors) # 包含yellow
colors.add('red') # 添加已存在的元素,无变化
print(colors)
# 删除元素
colors.remove('green')
print(colors) # 不包含green
# 安全删除(元素不存在时不报错)
colors.discard('purple') # purple不存在,但不报错
print(colors)
# 随机删除一个元素
random_color = colors.pop()
print(f"随机删除: {random_color}")
print(f"剩余集合: {colors}")
# 清空集合
colors.clear()
print(colors) # set()
集合的数学运算
集合支持丰富的数学运算,这些运算在实际问题中非常有用:
python
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
# 并集(union):包含两个集合的所有元素
union_set = set_a | set_b
print(f"并集: {union_set}") # {1, 2, 3, 4, 5, 6, 7, 8}
# 交集(intersection):包含两个集合的共同元素
intersection_set = set_a & set_b
print(f"交集: {intersection_set}") # {4, 5}
# 差集(difference):包含在第一个集合但不在第二个集合的元素
difference_set = set_a - set_b
print(f"差集: {difference_set}") # {1, 2, 3}
# 对称差集(symmetric difference):包含只在一个集合中的元素
symmetric_difference = set_a ^ set_b
print(f"对称差集: {symmetric_difference}") # {1, 2, 3, 6, 7, 8}
集合的关系运算
集合还支持各种关系测试:
python
set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
set_c = {1, 2}
# 子集判断
print(f"set_c是set_a的子集: {set_c.issubset(set_a)}") # True
print(f"set_c ⊆ set_a: {set_c <= set_a}") # True
# 真子集判断
print(f"set_c是set_a的真子集: {set_c < set_a}") # True
# 超集判断
print(f"set_b是set_a的超集: {set_b.issuperset(set_a)}") # True
print(f"set_b ⊇ set_a: {set_b >= set_a}") # True
# 真超集判断
print(f"set_b是set_a的真超集: {set_b > set_a}") # True
# 无交集判断
set_d = {6, 7, 8}
print(f"set_a和set_d无交集: {set_a.isdisjoint(set_d)}") # True
集合的应用场景
集合在实际编程中有很多实用场景:
-
数据去重: 快速去除列表中的重复元素
-
成员测试: 快速判断元素是否在集合中
-
数学运算: 进行集合的交、并、差等运算
-
数据筛选: 筛选满足条件的元素
-
关系测试: 测试集合间的包含关系
while循环详解
什么是while循环?
while循环是Python中的一种基本循环结构,它会在条件为真时重复执行代码块,直到条件变为假为止。while循环特别适合在不知道具体循环次数,但知道循环条件的情况下使用。
while循环的基本语法
while循环的语法结构很简单:
python
while 条件表达式:
循环体代码
当条件表达式为True时,执行循环体代码;执行完毕后再次检查条件表达式,如果仍然为True,则继续执行循环体,如此反复,直到条件表达式为False。
while循环的执行流程
为了更好地理解while循环的执行流程,我们可以看一个具体的例子:
python
# 打印1到5的数字
count = 1
while count <= 5:
print(f"当前数字: {count}")
count += 1 # 重要:更新循环变量
print("循环结束")
这个例子的执行流程是:
-
初始化count为1
-
检查count <= 5,为True,进入循环
-
打印当前数字
-
count增加1
-
重复步骤2-4,直到count为6时条件为False
-
执行循环后的代码
while循环的注意事项
使用while循环时需要特别注意几个问题:
1. 避免无限循环
python
# 危险的代码:忘记更新循环变量
# count = 1
# while count <= 5:
# print(count)
# # 忘记写 count += 1,导致无限循环
# 正确的做法
count = 1
while count <= 5:
print(count)
count += 1 # 必须更新循环变量
2. 使用break和continue控制循环
python
# break示例:在特定条件下立即退出循环
count = 1
while count <= 10:
if count == 6:
print("遇到6,提前退出循环")
break # 立即退出整个循环
print(count)
count += 1
# continue示例:跳过当前迭代,继续下一次
count = 0
while count < 5:
count += 1
if count == 3:
print("跳过3")
continue # 跳过本次循环的剩余代码
print(count)
3. while-else结构
python
# while循环正常结束时执行else块
count = 1
while count <= 3:
print(count)
count += 1
else:
print("循环正常结束")
# 如果循环被break中断,else块不会执行
count = 1
while count <= 5:
if count == 3:
break
print(count)
count += 1
else:
print("这行不会执行") # 因为循环被break中断
while循环的实用技巧
1. 使用标志变量控制循环
python
# 使用标志变量控制复杂循环
active = True
while active:
user_input = input("请输入命令(q退出): ")
if user_input == 'q':
active = False
elif user_input == 'help':
print("帮助信息...")
else:
print(f"执行命令: {user_input}")
2. 处理用户输入
python
# 使用while循环处理用户输入
while True:
age_input = input("请输入年龄: ")
if age_input.isdigit():
age = int(age_input)
if 0 <= age <= 150:
print(f"年龄: {age}")
break
else:
print("年龄必须在0-150之间")
else:
print("请输入有效的数字")
for循环详解
什么是for循环?
for循环是Python中另一种重要的循环结构,它主要用于遍历序列(如列表、元组、字符串)或其他可迭代对象。for循环的特点是知道要遍历的元素个数,按顺序处理每个元素。
for循环的基本语法
for循环的语法结构如下:
python
for 变量 in 可迭代对象:
循环体代码
每次循环时,变量会被赋值为可迭代对象中的下一个元素,然后执行循环体代码,直到遍历完所有元素。
for循环遍历不同类型的数据
for循环可以遍历各种可迭代对象:
python
# 遍历列表
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# 遍历字符串
text = "Python"
for char in text:
print(char)
# 遍历元组
points = (1, 2), (3, 4), (5, 6)
for x, y in points:
print(f"坐标: ({x}, {y})")
# 遍历字典
student = {'name': '张三', 'age': 18, 'score': 95}
for key in student:
print(f"{key}: {student[key]}")
# 更好的字典遍历方式
for key, value in student.items():
print(f"{key}: {value}")
range()函数的详细用法
range()函数是for循环的重要搭档,用于生成整数序列:
python
# 生成0-4的序列
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# 生成2-5的序列
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# 生成1-9的奇数序列
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
# 倒序序列
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
# 结合len()遍历列表索引
fruits = ['apple', 'banana', 'orange']
for i in range(len(fruits)):
print(f"索引{i}: {fruits[i]}")
for循环的高级用法
1. 使用enumerate()获取索引
python
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(f"索引{index}: {fruit}")
# 指定起始索引
for index, fruit in enumerate(fruits, start=1):
print(f"第{index}个水果: {fruit}")
2. 使用zip()同时遍历多个序列
python
names = ['张三', '李四', '王五']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}的成绩是{score}")
# 处理不等长序列
list1 = [1, 2, 3]
list2 = ['a', 'b']
for num, char in zip(list1, list2):
print(f"{num}-{char}") # 只遍历到较短的序列结束
3. for-else结构
python
# for循环正常结束时会执行else块
for i in range(3):
print(i)
else:
print("循环正常结束")
# 如果循环被break中断,else块不会执行
for i in range(5):
if i == 3:
break
print(i)
else:
print("这行不会执行")
循环控制语句详解
Python提供了三个循环控制语句,用于更精细地控制循环流程:
1. break语句break语句用于立即退出整个循环,不再执行循环中剩余的代码,也不进行下一次循环。
python
# 在列表中查找特定元素
numbers = [1, 3, 5, 7, 9, 2, 4, 6, 8]
target = 5
found = False
for num in numbers:
if num == target:
print(f"找到目标数字: {target}")
found = True
break # 找到后立即退出循环,提高效率
print(f"检查数字: {num}")
if not found:
print("未找到目标数字")
2. continue语句continue语句用于跳过当前迭代的剩余代码,直接开始下一次循环。
python
# 打印1-10中的奇数
for i in range(1, 11):
if i % 2 == 0: # 如果是偶数
continue # 跳过本次循环的剩余代码
print(i) # 只打印奇数
3. pass语句pass是空语句,什么都不做,主要用于保持代码结构的完整性。
python
# pass用作占位符
for i in range(5):
if i == 2:
pass # 暂时什么都不做,以后再来实现
else:
print(i)
循环的嵌套使用
循环可以嵌套使用,用于处理多维数据:
python
# 打印乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print() # 换行
# 处理二维列表
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=" ")
print()
实战演示
题目1:学生成绩管理系统
这个实战项目将综合运用字典、循环等知识点,实现一个完整的学生成绩管理系统:
python
print("=== 学生成绩管理系统 ===")
# 使用字典存储学生信息,键为学生姓名,值为成绩字典
students = {}
while True:
print("\n请选择操作:")
print("1. 添加学生")
print("2. 查看所有学生")
print("3. 查询学生成绩")
print("4. 删除学生")
print("5. 成绩统计")
print("6. 退出系统")
choice = input("请输入选择(1-6): ")
if choice == '1':
# 添加学生信息
name = input("请输入学生姓名: ").strip()
if not name:
print("姓名不能为空!")
continue
if name in students:
print("该学生已存在!")
continue
# 输入各科成绩
scores = {}
subjects = ['语文', '数学', '英语']
for subject in subjects:
while True:
score_input = input(f"请输入{subject}成绩: ")
if score_input.replace('.', '').isdigit():
score = float(score_input)
if 0 <= score <= 100:
scores[subject] = score
break
else:
print("成绩必须在0-100之间!")
else:
print("请输入有效的数字成绩!")
students[name] = scores
print(f"成功添加学生: {name}")
print(f"各科成绩: {scores}")
elif choice == '2':
# 查看所有学生信息
if not students:
print("暂无学生信息!")
else:
print("\n=== 所有学生信息 ===")
for name, scores in students.items():
total_score = sum(scores.values())
average_score = total_score / len(scores)
# 判断总评等级
if average_score >= 90:
grade = "优秀"
elif average_score >= 80:
grade = "良好"
elif average_score >= 70:
grade = "中等"
elif average_score >= 60:
grade = "及格"
else:
grade = "不及格"
print(f"姓名: {name}")
print(f" 各科成绩: {scores}")
print(f" 平均分: {average_score:.1f}, 等级: {grade}")
print("-" * 30)
elif choice == '3':
# 查询学生成绩
name = input("请输入要查询的学生姓名: ").strip()
if name in students:
scores = students[name]
total_score = sum(scores.values())
average_score = total_score / len(scores)
print(f"\n学生 {name} 的成绩信息:")
for subject, score in scores.items():
print(f" {subject}: {score}")
print(f" 总分: {total_score}, 平均分: {average_score:.1f}")
else:
print("该学生不存在!")
elif choice == '4':
# 删除学生
name = input("请输入要删除的学生姓名: ").strip()
if name in students:
del students[name]
print(f"已删除学生: {name}")
else:
print("该学生不存在!")
elif choice == '5':
# 成绩统计
if not students:
print("暂无学生信息!")
continue
print("\n=== 成绩统计 ===")
# 统计各科平均分
subjects = ['语文', '数学', '英语']
subject_totals = {subject: 0 for subject in subjects}
subject_counts = {subject: 0 for subject in subjects}
for scores in students.values():
for subject, score in scores.items():
subject_totals[subject] += score
subject_counts[subject] += 1
print("各科平均分:")
for subject in subjects:
if subject_counts[subject] > 0:
average = subject_totals[subject] / subject_counts[subject]
print(f" {subject}: {average:.1f}")
# 统计分数段
score_ranges = {'90-100': 0, '80-89': 0, '70-79': 0, '60-69': 0, '0-59': 0}
for scores in students.values():
total_score = sum(scores.values())
average_score = total_score / len(scores)
if average_score >= 90:
score_ranges['90-100'] += 1
elif average_score >= 80:
score_ranges['80-89'] += 1
elif average_score >= 70:
score_ranges['70-79'] += 1
elif average_score >= 60:
score_ranges['60-69'] += 1
else:
score_ranges['0-59'] += 1
print("\n平均分分布:")
for range_name, count in score_ranges.items():
percentage = (count / len(students)) * 100
print(f" {range_name}: {count}人 ({percentage:.1f}%)")
elif choice == '6':
print("感谢使用学生成绩管理系统,再见!")
break
else:
print("无效的选择,请重新输入!")
题目2:数据分析与统计系统
这个实战项目展示如何使用集合和循环进行复杂的数据分析:
python
print("=== 数据分析与统计系统 ===")
# 模拟多个班级的学生数据
class_a = {'张三', '李四', '王五', '赵六', '钱七'}
class_b = {'王五', '赵六', '孙八', '周九', '吴十'}
class_c = {'张三', '孙八', '郑十一', '王十二', '陈十三'}
print("原始数据:")
print(f"A班: {class_a}")
print(f"B班: {class_b}")
print(f"C班: {class_c}")
# 使用集合运算进行数据分析
print("\n=== 数据分析结果 ===")
# 1. 全校学生(所有班级的并集)
all_students = class_a | class_b | class_c
print(f"全校学生总数: {len(all_students)}")
print(f"全校学生名单: {sorted(all_students)}")
# 2. 多班级学生统计
multiple_classes = set()
for student in all_students:
class_count = 0
if student in class_a: class_count += 1
if student in class_b: class_count += 1
if student in class_c: class_count += 1
if class_count >= 2:
multiple_classes.add(student)
print(f"\n同时在多个班级的学生: {multiple_classes}")
print(f"人数: {len(multiple_classes)}")
# 3. 唯一班级学生
unique_students = all_students - multiple_classes
print(f"\n只在一个班级的学生: {unique_students}")
print(f"人数: {len(unique_students)}")
# 4. 班级关系分析
print("\n=== 班级关系分析 ===")
# 两两班级的交集
ab_intersection = class_a & class_b
ac_intersection = class_a & class_c
bc_intersection = class_b & class_c
print(f"A班和B班共同学生: {ab_intersection}")
print(f"A班和C班共同学生: {ac_intersection}")
print(f"B班和C班共同学生: {bc_intersection}")
# 5. 唯一班级学生统计
only_a = class_a - class_b - class_c
only_b = class_b - class_a - class_c
only_c = class_c - class_a - class_b
print(f"\n只在A班的学生: {only_a}")
print(f"只在B班的学生: {only_b}")
print(f"只在C班的学生: {only_c}")
# 6. 学生查询功能
while True:
print("\n=== 学生查询 ===")
search_name = input("请输入要查询的学生姓名(输入q退出): ")
if search_name.lower() == 'q':
break
if search_name in all_students:
classes = []
if search_name in class_a: classes.append('A班')
if search_name in class_b: classes.append('B班')
if search_name in class_c: classes.append('C班')
print(f"学生 {search_name} 在以下班级: {', '.join(classes)}")
if len(classes) >= 2:
print("⚠️ 该学生在多个班级!")
else:
print("该学生不在任何班级中")
print("\n数据分析完成!")
题目3:购物车优化系统
这个实战项目展示如何在实际应用中使用字典和循环:
python
print("=== 购物车优化系统 ===")
# 商品数据库
products = {
'001': {'name': '苹果', 'price': 5.5, 'stock': 100, 'category': '水果'},
'002': {'name': '香蕉', 'price': 3.0, 'stock': 80, 'category': '水果'},
'003': {'name': '牛奶', 'price': 8.0, 'stock': 50, 'category': '饮品'},
'004': {'name': '面包', 'price': 6.5, 'stock': 60, 'category': '食品'},
'005': {'name': '鸡蛋', 'price': 12.0, 'stock': 30, 'category': '食品'},
'006': {'name': '可乐', 'price': 3.5, 'stock': 120, 'category': '饮品'},
'007': {'name': '饼干', 'price': 4.0, 'stock': 90, 'category': '食品'}
}
# 购物车和用户数据
cart = {}
users = {
'admin': {'password': '123456', 'type': 'admin'},
'user1': {'password': '111111', 'type': 'customer'}
}
current_user = None
def display_products_by_category():
"""按分类显示商品"""
categories = {}
for product_id, info in products.items():
category = info['category']
if category not in categories:
categories[category] = []
categories[category].append((product_id, info))
print("\n=== 商品分类展示 ===")
for category, items in categories.items():
print(f"\n【{category}】")
for product_id, info in items:
print(f" {product_id}: {info['name']} - ¥{info['price']} (库存: {info['stock']})")
def search_products():
"""搜索商品"""
keyword = input("请输入搜索关键词: ").lower()
found_products = []
for product_id, info in products.items():
if (keyword in info['name'].lower() or
keyword in info['category'].lower() or
keyword in product_id):
found_products.append((product_id, info))
if found_products:
print(f"\n找到 {len(found_products)} 个相关商品:")
for product_id, info in found_products:
print(f" {product_id}: {info['name']} - ¥{info['price']} (库存: {info['stock']})")
else:
print("未找到相关商品")
def add_to_cart():
"""添加商品到购物车"""
display_products_by_category()
product_id = input("\n请输入要购买的商品ID: ")
if product_id in products:
product = products[product_id]
if product['stock'] <= 0:
print("该商品已售罄!")
return
while True:
quantity_input = input(f"请输入购买数量(库存{product['stock']}): ")
if quantity_input.isdigit():
quantity = int(quantity_input)
if quantity <= 0:
print("数量必须大于0!")
elif quantity > product['stock']:
print("库存不足!")
else:
# 检查购物车中是否已有该商品
if product_id in cart:
cart[product_id]['quantity'] += quantity
else:
cart[product_id] = {
'name': product['name'],
'price': product['price'],
'quantity': quantity,
'category': product['category']
}
print(f"成功添加 {product['name']} × {quantity} 到购物车")
break
else:
print("请输入有效的数量!")
else:
print("商品ID不存在!")
def view_cart():
"""查看购物车"""
if not cart:
print("购物车为空!")
return
print("\n=== 购物车内容 ===")
total_amount = 0
category_totals = {}
for product_id, item in cart.items():
item_total = item['price'] * item['quantity']
total_amount += item_total
# 按分类统计
category = item['category']
if category not in category_totals:
category_totals[category] = 0
category_totals[category] += item_total
print(f"{item['name']} | 单价:¥{item['price']} | 数量:{item['quantity']} | 小计:¥{item_total:.2f}")
print(f"\n分类统计:")
for category, amount in category_totals.items():
print(f" {category}: ¥{amount:.2f}")
print(f"\n购物车总计: ¥{total_amount:.2f}")
def checkout():
"""结算"""
if not cart:
print("购物车为空,无法结算!")
return
view_cart()
confirm = input("\n确认结算吗?(y/n): ")
if confirm.lower() == 'y':
# 更新库存
for product_id, item in cart.items():
products[product_id]['stock'] -= item['quantity']
total_amount = sum(item['price'] * item['quantity'] for item in cart.values())
print(f"\n结算成功! 总金额: ¥{total_amount:.2f}")
print("感谢您的购买!")
cart.clear()
else:
print("取消结算")
# 主程序
while True:
print("\n" + "="*50)
print("1. 用户登录")
print("2. 浏览商品")
print("3. 搜索商品")
print("4. 添加到购物车")
print("5. 查看购物车")
print("6. 结算")
print("7. 退出系统")
choice = input("请选择操作(1-7): ")
if choice == '1':
username = input("用户名: ")
password = input("密码: ")
if username in users and users[username]['password'] == password:
current_user = username
print(f"登录成功! 欢迎{username}")
else:
print("用户名或密码错误!")
elif choice == '2':
display_products_by_category()
elif choice == '3':
search_products()
elif choice == '4':
if current_user:
add_to_cart()
else:
print("请先登录!")
elif choice == '5':
if current_user:
view_cart()
else:
print("请先登录!")
elif choice == '6':
if current_user:
checkout()
else:
print("请先登录!")
elif choice == '7':
print("感谢使用购物车系统,再见!")
break
else:
print("无效的选择,请重新输入!")
每日一题
题目:简易ATM机系统
题目描述:
创建一个简单的ATM机模拟系统,实现基本的银行账户操作功能。
基本功能要求:
-
用户登录:输入账号和密码进行登录验证
-
余额查询:查看当前账户余额
-
存款功能:向账户存入金额
-
取款功能:从账户取出金额(需验证余额)
-
退出系统:安全退出ATM系统
数据存储要求:
-
使用字典存储用户账户信息
-
每个用户包含:账号、密码、余额
-
示例数据格式:
python
accounts = {
'1001': {'password': '123456', 'balance': 5000},
'1002': {'password': '111111', 'balance': 3000}
}
系统要求:
-
使用while循环实现主菜单
-
使用if-else进行条件判断
-
实现基本的输入验证
-
提供清晰的操作提示
界面示例:
python
=== 欢迎使用ATM机系统 ===
请选择操作:
1. 用户登录
2. 退出系统
请输入选择(1-2):
扩展功能(可选):
-
添加新用户注册功能
-
实现交易记录
-
添加密码修改功能
-
实现账户锁定机制(密码错误次数限制)
这个简易版的ATM机系统专注于核心功能,适合初学者练习字典、循环和条件判断的基本用法。
欢迎在评论区进行打卡留言,并分享学习经验,题目讲解以及分享更多内容,关注博主或者订阅专栏,可以第一时间看到博主的发表博文,感谢大家支持,我们下期见!