如何用Python编写一个实现学生选课系统功能,包括增加课程、删除课程、修改课程和显示课程列表以及用户退出的代码示例?
时间: 2024-11-18 19:15:44 浏览: 80
下面是一个简化的Python实现学生选课系统的基本功能,使用字典来模拟学生和课程的数据结构:
```python
import os
# 定义一个简单的学生类
class Student:
def __init__(self, name, courses=None):
self.name = name
if courses is None:
self.courses = {}
else:
self.courses = courses
# 功能函数
def enroll(self, course, grade):
self.courses[course] = grade
print(f'{self.name}已选修了{course},成绩为{grade}')
def drop(self, course):
if course in self.courses:
del self.courses[course]
print(f'{self.name}已取消选修{course}')
else:
print(f'{self.name}尚未选修{course}')
def view_courses(self):
print(f'{self.name}的课程:')
for course, grade in self.courses.items():
print(f'{course}: {grade}')
def quit(self):
print(f'{self.name}已退出系统')
os._exit(0) # 使用os._exit而非直接sys.exit,避免影响后续脚本运行
# 示例使用
def main():
students = {} # 存储所有学生
while True:
user_input = input("请输入你的命令 (enroll/drop/view/quit): ")
if user_input == 'quit':
break
parts = user_input.split(' ')
if len(parts) != 2:
print("无效命令,请输入正确的格式")
continue
command, data = parts[0], parts[1]
if command not in ['enroll', 'drop', 'view']:
print("未知命令")
continue
if command == 'enroll':
if data in students:
student = students[data]
grade = int(input("请输入分数: "))
student.enroll(data, grade)
else:
print(f'{data}不存在')
elif command == 'drop':
if data in students:
student = students[data]
student.drop(data)
else:
print(f'{data}不存在')
elif command == 'view':
if data in students:
student = students[data]
student.view_courses()
else:
print(f'{data}不存在')
if __name__ == '__main__':
main()
```
阅读全文