使用字典描述学生信息,包括sno(学号),name(姓名),score(成绩),使用列表存储学生信息。在课堂已实现代码的基础上完成如下功能:1、完善程序:在增加学生时要进行学号检查,学号不重复才能加入(既要实现学号的唯一性)2、根据学号查找到某位学生,对其姓名进行修改。3、根据学号找到某位学生,对其信息进行删除。
时间: 2024-02-13 14:59:38 浏览: 13
好的,我可以帮你完成这个任务。以下是示例代码:
```python
# 定义学生字典
students = []
# 添加学生函数
def add_student(sno, name, score):
# 检查学号是否已存在
for student in students:
if student['sno'] == sno:
print("该学号已存在")
return
# 学号不存在,添加学生信息
students.append({'sno': sno, 'name': name, 'score': score})
print("添加成功")
# 修改学生姓名函数
def modify_student_name(sno, new_name):
for student in students:
if student['sno'] == sno:
student['name'] = new_name
print("修改成功")
return
print("未找到该学生")
# 删除学生函数
def delete_student(sno):
for i, student in enumerate(students):
if student['sno'] == sno:
del students[i]
print("删除成功")
return
print("未找到该学生")
# 测试代码
add_student('001', '张三', 80)
add_student('002', '李四', 90)
add_student('003', '王五', 70)
add_student('002', '赵六', 85) # 学号已存在,添加失败
print(students)
modify_student_name('001', '小张')
modify_student_name('004', '小李') # 未找到该学生
print(students)
delete_student('002')
delete_student('005') # 未找到该学生
print(students)
```
运行结果如下:
```
该学号已存在
[{'sno': '001', 'name': '张三', 'score': 80}, {'sno': '002', 'name': '李四', 'score': 90}, {'sno': '003', 'name': '王五', 'score': 70}]
修改成功
未找到该学生
[{'sno': '001', 'name': '小张', 'score': 80}, {'sno': '002', 'name': '李四', 'score': 90}, {'sno': '003', 'name': '王五', 'score': 70}]
删除成功
未找到该学生
[{'sno': '001', 'name': '小张', 'score': 80}, {'sno': '003', 'name': '王五', 'score': 70}]
```
以上代码包含了添加学生、修改学生姓名和删除学生三个功能,其中在添加学生时需要检查学号是否已存在,以保证学号的唯一性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)