使用字典描述学生信息,包括sno(学号),name(姓名),score(成绩),使用列表存储学生信息。在课堂已实现代码的基础上完成如下功能:1、完善程序:在增加学生时要进行学号检查,学号不重复才能加入(既要实现学号的唯一性) 2、根据学号查找到某位学生,对其姓名进行修改。3、根据学号找到某位学生,对其信息进行删除。
时间: 2024-02-12 12:04:14 浏览: 51
好的,以下是代码实现:
```python
students = []
def add_student(sno, name, score):
for stu in students:
if stu['sno'] == sno:
print("Error: 学号已存在")
return
students.append({'sno': sno, 'name': name, 'score': score})
print("添加成功")
def modify_name(sno, new_name):
for stu in students:
if stu['sno'] == sno:
stu['name'] = new_name
print("修改成功")
return
print("Error: 学号不存在")
def delete_student(sno):
for stu in students:
if stu['sno'] == sno:
students.remove(stu)
print("删除成功")
return
print("Error: 学号不存在")
```
在上面的代码中,我们定义了一个列表 `students` 来存储学生信息,每个学生信息是一个字典,包含学号、姓名和成绩三个键值。接下来分别实现了增加学生、修改姓名和删除学生三个功能:
1. `add_student(sno, name, score)`:添加学生函数,首先遍历列表 `students`,如果学号已经存在,输出错误信息;否则将新学生信息加入到列表中,并输出添加成功信息。
2. `modify_name(sno, new_name)`:修改姓名函数,首先遍历列表 `students`,如果学号不存在,输出错误信息;否则修改学生信息中的姓名键值,输出修改成功信息。
3. `delete_student(sno)`:删除学生函数,首先遍历列表 `students`,如果学号不存在,输出错误信息;否则从列表中删除该学生信息,输出删除成功信息。
注意:为了实现学号的唯一性,我们在添加学生时需要遍历列表中已有的学生信息。如果学生数量很多,这种方法会导致效率低下,可以考虑使用其他数据结构来提高查询速度。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)