实用指南:Python全栈(基础篇)——Day05:后端内容(dict与set+while循环+for循环+实战演示+每日一题)

news/2025/10/21 18:06:29/文章来源:https://www.cnblogs.com/yxysuanfa/p/19156090

目录

字典(dict)详解

什么是字典?

字典的基本特性

字典的创建方式

字典的访问操作

字典的修改和更新

字典的删除操作

字典的遍历操作

字典的常用方法总结

字典的应用场景

集合(set)详解

什么是集合?

集合的创建方式

集合的基本操作

集合的数学运算

集合的关系运算

集合的应用场景

while循环详解

什么是while循环?

while循环的基本语法

while循环的执行流程

while循环的注意事项

while循环的实用技巧

for循环详解

什么是for循环?

for循环的基本语法

for循环遍历不同类型的数据

range()函数的详细用法

for循环的高级用法

循环控制语句详解

循环的嵌套使用

实战演示

题目1:学生成绩管理系统

题目2:数据分析与统计系统

题目3:购物车优化系统

每日一题

题目:简易ATM机系统

题目描述:

基本功能要求:

数据存储要求:

系统要求:

界面示例:

扩展功能(可选):


欢迎在评论区进行打卡留言,并分享学习经验,题目讲解以及分享更多内容,关注博主或者订阅专栏,可以第一时间看到博主发表的博文

字典(dict)详解

什么是字典?

字典是Python中非常重要的一种数据结构,它采用键值对(key-value)的形式来存储数据。字典在其他编程语言中也被称为映射(map)、哈希表(hash table)或关联数组。

字典的核心思想是通过键来快速查找对应的值,这种查找速度非常快,几乎不受字典大小的影响。这是因为字典内部使用了哈希表的数据结构,通过计算键的哈希值来直接定位存储位置。

字典的基本特性

字典使用大括号{}来创建,每个键值对用冒号:分隔,不同的键值对用逗号,分隔。键和值可以是任意类型,但键必须是不可变类型。

为什么键必须是不可变类型?这是因为字典通过哈希表实现,哈希表要求键的值不能改变,否则哈希值会改变,导致无法正确找到对应的值。因此,字符串、数字、元组等不可变类型可以作为键,而列表、字典等可变类型不能作为键。

字典的创建方式

字典有多种创建方式,每种方式都有其适用场景:

# 方法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)}

字典的访问操作

访问字典元素有多种方法,每种方法都有不同的特性和适用场景:

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}

字典的修改和更新

字典是可变数据类型,可以随时添加、修改和删除元素:

# 添加新键值对
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

字典的删除操作

删除字典元素也有多种方法,需要根据具体需求选择:

# 方法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)  # 空字典{}

字典的遍历操作

遍历字典时,可以根据需要选择遍历键、值或键值对:

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(): 浅拷贝字典

字典的应用场景

字典在实际编程中有广泛的应用:

  1. 配置信息存储: 存储程序的配置参数

  2. 数据缓存: 缓存计算结果,提高程序性能

  3. 计数统计: 统计元素出现次数

  4. 数据分组: 按某个属性对数据进行分组

  5. 对象表示: 表示复杂对象的属性

集合(set)详解

什么是集合?

集合是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()

集合的基本操作

集合支持丰富的操作来管理元素:

# 创建测试集合
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()

集合的数学运算

集合支持丰富的数学运算,这些运算在实际问题中非常有用:

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}

集合的关系运算

集合还支持各种关系测试:

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

集合的应用场景

集合在实际编程中有很多实用场景:

  1. 数据去重: 快速去除列表中的重复元素

  2. 成员测试: 快速判断元素是否在集合中

  3. 数学运算: 进行集合的交、并、差等运算

  4. 数据筛选: 筛选满足条件的元素

  5. 关系测试: 测试集合间的包含关系

while循环详解

什么是while循环?

while循环是Python中的一种基本循环结构,它会在条件为真时重复执行代码块,直到条件变为假为止。while循环特别适合在不知道具体循环次数,但知道循环条件的情况下使用。

while循环的基本语法

while循环的语法结构很简单:

while 条件表达式:   循环体代码

当条件表达式为True时,执行循环体代码;执行完毕后再次检查条件表达式,如果仍然为True,则继续执行循环体,如此反复,直到条件表达式为False。

while循环的执行流程

为了更好地理解while循环的执行流程,我们可以看一个具体的例子:

# 打印1到5的数字
count = 1
while count <= 5:   print(f"当前数字: {count}")   count += 1  # 重要:更新循环变量
print("循环结束")

这个例子的执行流程是:

  1. 初始化count为1

  2. 检查count <= 5,为True,进入循环

  3. 打印当前数字

  4. count增加1

  5. 重复步骤2-4,直到count为6时条件为False

  6. 执行循环后的代码

while循环的注意事项

使用while循环时需要特别注意几个问题:

1. 避免无限循环

# 危险的代码:忘记更新循环变量
# count = 1
# while count <= 5:
#     print(count)
#     # 忘记写 count += 1,导致无限循环
​
# 正确的做法
count = 1
while count <= 5:   print(count)   count += 1  # 必须更新循环变量

2. 使用break和continue控制循环

# 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结构

# 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. 使用标志变量控制循环

# 使用标志变量控制复杂循环
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. 处理用户输入

# 使用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循环的语法结构如下:

for 变量 in 可迭代对象:   循环体代码

每次循环时,变量会被赋值为可迭代对象中的下一个元素,然后执行循环体代码,直到遍历完所有元素。

for循环遍历不同类型的数据

for循环可以遍历各种可迭代对象:

# 遍历列表
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循环的重要搭档,用于生成整数序列:

# 生成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()获取索引

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()同时遍历多个序列

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结构

# 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语句用于立即退出整个循环,不再执行循环中剩余的代码,也不进行下一次循环。

# 在列表中查找特定元素
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语句用于跳过当前迭代的剩余代码,直接开始下一次循环。

# 打印1-10中的奇数
for i in range(1, 11):   if i % 2 == 0:  # 如果是偶数       continue    # 跳过本次循环的剩余代码   print(i)        # 只打印奇数

3. pass语句pass是空语句,什么都不做,主要用于保持代码结构的完整性。

# pass用作占位符
for i in range(5):   if i == 2:       pass  # 暂时什么都不做,以后再来实现   else:       print(i)

循环的嵌套使用

循环可以嵌套使用,用于处理多维数据:

# 打印乘法表
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:学生成绩管理系统

这个实战项目将综合运用字典、循环等知识点,实现一个完整的学生成绩管理系统:

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:数据分析与统计系统

这个实战项目展示如何使用集合和循环进行复杂的数据分析:

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:购物车优化系统

这个实战项目展示如何在实际应用中使用字典和循环:

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机模拟系统,实现基本的银行账户操作功能。

基本功能要求:

  1. 用户登录:输入账号和密码进行登录验证

  2. 余额查询:查看当前账户余额

  3. 存款功能:向账户存入金额

  4. 取款功能:从账户取出金额(需验证余额)

  5. 退出系统:安全退出ATM系统

数据存储要求:

  • 使用字典存储用户账户信息

  • 每个用户包含:账号、密码、余额

  • 示例数据格式:

accounts = {   '1001': {'password': '123456', 'balance': 5000},   '1002': {'password': '111111', 'balance': 3000}
}

系统要求:

  • 使用while循环实现主菜单

  • 使用if-else进行条件判断

  • 实现基本的输入验证

  • 提供清晰的操作提示

界面示例:

=== 欢迎使用ATM机系统 ===
请选择操作:
1. 用户登录
2. 退出系统
请输入选择(1-2):

扩展功能(可选):

  • 添加新用户注册功能

  • 实现交易记录

  • 添加密码修改功能

  • 实现账户锁定机制(密码错误次数限制)

这个简易版的ATM机系统专注于核心功能,适合初学者练习字典、循环和条件判断的基本用法。

欢迎在评论区进行打卡留言,并分享学习经验,题目讲解以及分享更多内容,关注博主或者订阅专栏,可以第一时间看到博主的发表博文,感谢大家支持,我们下期见!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/942536.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在AI技术唾手可得的时代,挖掘新需求成为开发者核心竞争力——某知名API学习平台需求洞察

本文深入分析了一个开源API学习平台的核心功能和应用场景,通过系统梳理用户反馈和功能需求,揭示了在AI技术快速发展的背景下,如何识别和满足开发者真实需求的重要性,为技术产品规划提供参考价值。a.内容描述核心功…

KeyShot许可安全性保障

在数字化时代,软件的安全性成为了企业和个人选择软件的关键因素之一。KeyShot作为一款广受欢迎的3D渲染软件,深知安全性对于用户的重要性。为了确保您的KeyShot许可安全无忧,我们采取了一系列严格的安全措施,为您的…

maven添加自己下载的jar到本地仓库

1、 打开Maven中央仓库网站: https://mvnrepository.com/ 或者阿里云 https://maven.aliyun.com/mvn/guide 搜索并下载对应的jar到本地 2、 运行Maven命令,以确保JAR文件已成功安装到本地仓库。 例:mvn install:ins…

2025年防静电/劳保/国网/餐厅/工厂/电工/防酸碱/电力/车间/航空/员工广告衫,文化衫/t恤/polo衫/冲锋衣厂家推荐排行榜

2025年防静电/劳保/国网/餐厅/工厂/电工/防酸碱/电力/车间/航空/员工广告衫,文化衫/t恤/polo衫/冲锋衣厂家推荐排行榜 行业背景与发展趋势 随着产业升级和安全生产意识的提升,特种工装与职业服饰市场正迎来新一轮发展…

【往届已检索!稳定检索】2025年第二届人工智能、数字媒体技术与交互设计国际学术会议(ICADI 2025)

2025年第二届人工智能、数字媒体技术与交互设计国际学术会议(ICADI 2025) 2025 2nd International Conference on Artificial Intelligence, Digital Media Technology and Interaction Design ACM独立出版!快见刊,…

苹果最折腾的功能!iPhone快捷指令分享

下面列举一些我在生活中会使用的iPhone的快捷指令。 这种系统级的自动化真的有点强,它可以通过Siri、下拉控制中心、设置背部敲击、超级按钮等快捷的启动方式。 自动同步待办 对于多端同步使用待办这件事,真的是头疼…

2025 年螺旋地桩源头厂家最新推荐排行榜:聚焦热镀锌光伏大棚等领域,精选优质企业保障供应与品质光伏/大棚/预埋/ 定做/钢管螺旋地桩厂家推荐

引言 随着新能源基建、建筑工程、农林牧渔等领域对螺旋地桩的需求日益增长,采购方在选择源头厂家时面临诸多难题。市场上部分厂家缺乏完善生产体系与质控标准,产品质量不稳定,且存在层层加价、供货不及时、售后缺失…

交互题

有时你会在编程比赛里遇到交互题(包括CF) 在这种问题中,输入的数据可能不是预先定好的,但是是为你的解答量身定做的。 评测人写了一个特殊的程序——interactor,这样它的输出对应着你的程序的输入,而你的输出又对…

尝试理解FunctionalInterface

尝试理解FunctionalInterface$(".postTitle2").removeClass("postTitle2").addClass("singleposttitle");在网上找了例子,自己改改,写写,注释注释。下面把我对functionalinterface里…

2025 年防淹门源头厂家最新推荐排行榜权威发布,含地铁 / 防洪 / 地下通道专用款,15 项专利 + 央视报道品牌领衔

引言 当前全球气候变暖加剧,极端降雨引发的城市内涝灾害频发,地铁、地下车库、江河堤坝等关键区域对防淹门的需求愈发迫切。但防淹门市场乱象丛生,部分厂家用劣质材料生产的产品抗压抗折弯性能不足,还有厂家因缺乏…

一文带你掌握Visual Studio中集成的git功能

前言 Visual Studio中深度集成了git功能,可以很方便的进行源代码版本控制功能。 大部分日常的操作我们可以通过界面来完成,这样就省去了输入git命令的时间,也可以不用记很多参数。 但这毕竟是辅助工具,掌握常用的g…

2025年手持光谱仪厂家权威推荐榜:光谱分析仪/便携式光谱仪、矿石元素分析、合金金属不锈钢铝合金、贵金属三元催化检测设备精选

2025年手持光谱仪厂家权威推荐榜:光谱分析仪/便携式光谱仪、矿石元素分析、合金金属不锈钢铝合金、贵金属三元催化检测设备精选 行业技术发展现状与趋势 手持光谱仪作为现代工业检测领域的重要工具,其技术迭代速度正…

高级程序语言设计课程第二次作业

这个作业属于哪个课程:https://edu.cnblogs.com/campus/fzu/gjyycx 这个作业要求在哪里:https://www.cnblogs.com/zhuyuchen818/p/19155507 学号: 102500325 姓名:李志鹏 编写并运行书本第3章3.11 编程练习题目中的…

2025年定型机厂家推荐排行榜,拉幅定型机/门富士,节能定型机/余热回收,废气回收/烟气回收,智能排风/双层定型机源头企业深度解析

2025年定型机厂家推荐排行榜,拉幅定型机/门富士,节能定型机/余热回收,废气回收/烟气回收,智能排风/双层定型机源头企业深度解析 在纺织印染行业持续转型升级的背景下,定型机作为后整理工序的核心装备,其技术水平…

iOS 混淆实战 多工具组合完成 IPA 混淆、加固与工程化落地(iOS混淆|IPA加固|无源码混淆|Ipa Guard|Swift Shield)

本文以对话与实战流程还原 iOS 混淆落地:用 MobSF/class-dump 做静态发现,Swift Shield(可选)做源码混淆,Ipa Guard 做成品 IPA 混淆,Fastlane/Jenkins 自动化流水线,Frida/Hopper 动态验证,映射表由 KMS 管理…

单提交智能评审上线!用云效精准定位复杂 MR 代码问题

随着代码评审进入智能化时代,AI 已成为提升 Code Review 效率与代码质量的重要助手。但当一次合并请求(MR)包含大量提交或巨量变更时,把所有 diff 一次性交给 AI 审查,容易导致判断失真、遗漏细节或误解改动意图。…

ubuntu安装nvidia驱动 - Leonardo

一、驱动安装 1.驱动安装 方法一:使用官方 NVIDIA 仓库(推荐) sudo add-apt-repository ppa:graphics-drivers/ppa sudo apt update ubuntu-drivers devices sudo ubuntu-drivers autoinstall sudo reboot方法二:使…

十五、深入理解 SELinux - 指南

十五、深入理解 SELinux - 指南2025-10-21 17:49 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !importa…

2025 年少儿英语品牌口碑排行榜最新发布:欧美外教 + 原版教材甄选,含最新推荐及靠谱选择指南

引言 随着家长对少儿英语教育重视程度不断提升,市场上各类少儿英语品牌数量激增,但质量却良莠不齐,给家长选择带来极大困扰。部分品牌存在外教非母语、教龄短,难以营造纯正语言环境;教材脱离国际标准与国内应试需…

GitLab小坑:remote: GitLab: You are not allowed to create protected branches on this project.

git -c credential.helper= -c core.quotepath=false -c log.showSignature=false push --progress --porcelain origin refs/heads/release-xxx-0.4:release-abc这个本地提交push到新分支时,idea生成的git命令。然而…