当前位置:   article > 正文

Python学生信息管理系统,面向对象编程,面向过程编程_python面向对象信息管理系统

python面向对象信息管理系统

目录

Python学生信息管理系统

面向过程

面向对象


Python学生信息管理系统

面向过程

  1. import os.path
  2. import re
  3. filename = "students.txt"
  4. def main():
  5. ctrl = True # 标记是否退出系统
  6. while ctrl:
  7. menu() # 显示菜单————调用菜单方法
  8. option = input("请选择:")
  9. option_str = re.sub("\D", "", option)
  10. if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
  11. option_int = int(option_str)
  12. if option_int == 0:
  13. print("您已退出学生信息管理系统!")
  14. ctrl = False
  15. elif option_int == 1:
  16. insert()
  17. elif option_int == 2:
  18. search()
  19. elif option_int == 3:
  20. delete()
  21. elif option_int == 4:
  22. modify()
  23. elif option_int == 5:
  24. sort()
  25. elif option_int == 6:
  26. total()
  27. elif option_int == 7:
  28. show()
  29. def menu():
  30. print(
  31. "------------------------学生信息管理系统------------------------"
  32. "| |"
  33. "|==========================功能菜单============================"
  34. "| |"
  35. "| 1.录入学生信息 |"
  36. "| 2.查找学生信息 |"
  37. "| 3.删除学生信息 |"
  38. "| 4.修改学生信息 |"
  39. "| 5.排序 |"
  40. "| 6.统计学生总人数 |"
  41. "| 7.显示所有学生信息 |"
  42. "| 0.退出系统 |"
  43. "|============================================================"
  44. "| 说明:通过数字键上下选择菜单 |"
  45. "---------------------------------------------------------------"
  46. )
  47. # 将学生信息保存到文件
  48. def save(student):
  49. try:
  50. student_txt = open(filename, "a")
  51. except Exception as e:
  52. student_txt = open(filename, "w")
  53. for info in student:
  54. student_txt.write(str(info) + "\n")
  55. student_txt.close()
  56. # 实现学生信息录入功能
  57. def insert():
  58. stdentList = []
  59. mark = True
  60. while mark:
  61. id = input("请输入ID(如 1001):")
  62. if not id:
  63. break
  64. name = input("请输入名字:")
  65. if not name:
  66. break
  67. try:
  68. english = int(input("请输入英语成绩:"))
  69. python = int(input("请输入Python成绩:"))
  70. c = int(input("请输入c语言成绩:"))
  71. except:
  72. print("输入无效,不是整数值....重新录入信息")
  73. continue
  74. stdent = {"id": id, "name": name, "english": english, "python": python, "c": c}
  75. stdentList.append(stdent)
  76. inputMark = input("是否继续添加?(y/n):")
  77. if inputMark == "y":
  78. mark = True
  79. else:
  80. mark = False
  81. save(stdentList)
  82. print("学生信息录入完毕!!!")
  83. # 删除学生信息
  84. def delete():
  85. mark = True
  86. while mark:
  87. studentId = input("请输入要删除的学生ID: ")
  88. if (studentId != ""):
  89. if os.path.exists(filename):
  90. with open(filename, 'r') as rfile:
  91. student_old = rfile.readlines()
  92. else:
  93. student_old = []
  94. ifdel = False
  95. if student_old:
  96. with open(filename, 'w') as wfile:
  97. d = {}
  98. for list in student_old:
  99. d = dict(eval(list))
  100. if d['id'] != studentId:
  101. wfile.write(str(d) + "\n")
  102. else:
  103. ifdel = True
  104. if ifdel:
  105. print("ID为 %s 的学生信息已经被删除..." % studentId)
  106. else:
  107. print("没有找到ID为 %s 的学生信息..." % studentId)
  108. else:
  109. print("无学生信息...")
  110. break
  111. show()
  112. inputMark = input("是否继续删除? (y/n):")
  113. if inputMark == "y":
  114. mark = True
  115. else:
  116. mark = False
  117. # 修改学生信息
  118. def modify():
  119. show()
  120. if os.path.exists(filename):
  121. with open(filename, 'r') as rfile:
  122. student_old = rfile.readlines()
  123. else:
  124. return
  125. studentid = input("请输入要修改的学生ID: ")
  126. with open(filename, 'w') as wfile:
  127. for student in student_old:
  128. d = dict(eval(student))
  129. if d["id"] == studentid:
  130. print("找到了这名学生,可以修改他的信息!")
  131. while True:
  132. try:
  133. d["name"] = input("请输入姓名: ")
  134. d["english"] = int(input("请输入英语成绩: "))
  135. d["python"] = int(input("请输入Python成绩: "))
  136. d["c"] = int(input("请输入C语言成绩: "))
  137. except:
  138. print("您的输入有误,请重新输入。")
  139. else:
  140. break
  141. student = str(d)
  142. wfile.write(student + "\n")
  143. print("修改成功! ")
  144. else:
  145. wfile.write(student)
  146. mark = input("是否继续修改其他学生信息? (y/n):")
  147. if mark == "y":
  148. modify()
  149. # 查询学生信息
  150. def search():
  151. mark = True
  152. student_query = []
  153. while mark:
  154. id = ""
  155. name = ""
  156. if os.path.exists(filename):
  157. mode = input("按ID查输入1;按姓名查输入2: ")
  158. if mode == "1":
  159. id = input("请输入学生ID: ")
  160. elif mode == "2":
  161. name = input("请输入学生姓名: ")
  162. else:
  163. print("您的输入有误,请重新输入!")
  164. search()
  165. with open(filename, 'r') as file:
  166. student = file.readlines()
  167. for list in student:
  168. d = dict(eval(list))
  169. if (id != ""):
  170. if d['id'] == id:
  171. student_query.append(d)
  172. elif (name != ""):
  173. if d['name'] == name:
  174. student_query.append(d)
  175. show_student(student_query)
  176. student_query.clear()
  177. inputMark = input("是否继续查询?(y/n):")
  178. if inputMark == "y":
  179. mark = True
  180. else:
  181. mark = False
  182. else:
  183. print("暂未保存数据信息...")
  184. return
  185. # 统计学生总人数
  186. def total():
  187. if os.path.exists(filename):
  188. with open(filename, "r") as rfile:
  189. student_old = rfile.readlines()
  190. if student_old:
  191. print("一共有%d名学生!" % len(student_old))
  192. else:
  193. print("还没录入学生信息!")
  194. else:
  195. print("暂未保存数据信息。。。")
  196. # 显示所有学生信息
  197. def show():
  198. student_new = []
  199. if os.path.exists(filename):
  200. with open(filename, "r") as rfile:
  201. student_old = rfile.readlines()
  202. for list in student_old:
  203. student_new.append(eval(list))
  204. if student_new:
  205. show_student(student_new)
  206. def show_student(studentList):
  207. if not studentList:
  208. print("(o@.@o) 无数据信息 (o@.@o) \n")
  209. return
  210. # 定义标题显示格式
  211. format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^10}"
  212. print(format_title.format("ID", "名字", "英语成绩", "Python成绩", "C语言成绩", "总成绩"))
  213. # 定义具体内容显示格式
  214. format_data = "{:^6}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
  215. for info in studentList:
  216. print(format_data.format(info.get("id"),
  217. info.get("name"), str(info.get("english")), str(info.get("python")),
  218. str(info.get("c")),
  219. str(info.get("english") + info.get("python") +
  220. info.get("c")).center(12)))
  221. # 排序
  222. def sort():
  223. show()
  224. if os.path.exists(filename):
  225. with open(filename, "r") as file:
  226. student_old = file.readlines()
  227. student_new = []
  228. for list in student_old:
  229. d = dict(eval(list))
  230. student_new.append(d)
  231. else:
  232. return
  233. ascORdesc = input("请选择(0升序;1降序):")
  234. if ascORdesc == "0":
  235. ascORdescBool = False
  236. elif ascORdesc == "1":
  237. ascORdescBool = True
  238. else:
  239. print("你的输入有误,请重新输入")
  240. sort()
  241. mode = input("请选择排序方法(1按英语成绩排序;2按python成绩排序;3按c语言成绩排序;0按总成绩排序)")
  242. if mode == "1":
  243. student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)
  244. elif mode == "2":
  245. student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool)
  246. elif mode == "3":
  247. student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool)
  248. elif mode == "0":
  249. student_new.sort(key=lambda x: x["english"] + x["python"] + x["python"], reverse=ascORdescBool)
  250. else:
  251. print("您输入有误,请重新输入!")
  252. sort()
  253. show_student(student_new)
  254. if __name__ == '__main__':
  255. main()

面向对象

  1. # @Project : 学生信息管理系统
  2. # @Author : 黄前程
  3. # @Time : 2023/10/17 21:00
  4. # 请尊重作者的劳动成果,转载请注明出处
  5. # -----------------------------------------------
  6. class Student:
  7. def __init__(self, id, name, age, english, python, c):
  8. self.id = id
  9. self.name = name
  10. self.age = age
  11. self.english = english
  12. self.python = python
  13. self.c = c
  14. # __str__方法用于返回对象的描述信息,如果不使用__str__方法,直接print,或者return,返回的是对象的内存地址。
  15. # 如果在__str__中定义了描述信息,print或者return时,返回的就不是内存地址,显示更友好,实现了类到字符串的转化。
  16. def __str__(self):
  17. return (f"ID: {self.id:<6} | Name: {self.name:<10} | Age: {self.age:<6} "
  18. f"| English: {self.english:<6} | Python: {self.python:<6} | C: {self.c:<6}")
  19. class StudentManager:
  20. def __init__(self, file_name):
  21. self.students = []
  22. self.file_name = file_name
  23. try:
  24. with open(file_name, "r") as file:
  25. for line in file:
  26. student_info = line.strip().split(",")
  27. student = Student(student_info[0], student_info[1], int(student_info[2]), float(student_info[3]),
  28. float(student_info[4]), float(student_info[5]))
  29. self.students.append(student)
  30. except FileNotFoundError:
  31. print("系统中没有学生信息,请先录入学生信息!")
  32. def save_to_file(self):
  33. with open(self.file_name, "w") as file:
  34. for student in self.students:
  35. file.write(
  36. f"{student.id},{student.name},{student.age},{student.english},{student.python},{student.c}\n")
  37. def add_student(self, student):
  38. self.students.append(student)
  39. self.save_to_file()
  40. def delete_student(self, id):
  41. self.students = [student for student in self.students if student.id != id]
  42. self.save_to_file()
  43. def update_student(self, id, new_info):
  44. for student in self.students:
  45. if student.id == id:
  46. student.name = new_info[0]
  47. student.age = int(new_info[1])
  48. student.english = float(new_info[2])
  49. student.python = float(new_info[3])
  50. student.c = float(new_info[4])
  51. self.save_to_file()
  52. break
  53. def sort_students(self):
  54. self.students.sort(key=lambda student: student.english + student.python + student.c, reverse=True)
  55. def count_students(self):
  56. return len(self.students)
  57. def show_all_students(self):
  58. for student in self.students:
  59. print(student)
  60. def show_student(self, id):
  61. for student in self.students:
  62. if student.id == id:
  63. print(student)
  64. break
  65. def main():
  66. manager = StudentManager("students.txt")
  67. while True:
  68. print('''
  69. ------------------------学生信息管理系统------------------------
  70. | |
  71. |==========================功能菜单===========================|
  72. | |
  73. | 1.录入学生信息 |
  74. | 2.查找学生信息 |
  75. | 3.删除学生信息 |
  76. | 4.修改学生信息 |
  77. | 5.排序(成绩从高到低) |
  78. | 6.统计学生总人数 |
  79. | 7.显示所有学生信息 |
  80. | 0.退出系统 |
  81. |============================================================|
  82. | |
  83. ---------------------------------------------------------------
  84. '''
  85. )
  86. option = input("请选择:")
  87. if option == "1":
  88. while True:
  89. try:
  90. id = input("请输入学生ID: ")
  91. name = input("请输入学生姓名: ")
  92. age = int(input("请输入学生年龄: "))
  93. english = float(input("请输入英语成绩: "))
  94. python = float(input("请输入Python成绩: "))
  95. c = float(input("请输入C语言成绩: "))
  96. except:
  97. print("您的输入有误,请重新输入。")
  98. else:
  99. break
  100. manager.add_student(Student(id, name, age, english, python, c))
  101. elif option == "2":
  102. id = input("请输入要查询的学生ID: ")
  103. if id in [student.id for student in manager.students]:
  104. print(f"学生在系统中")
  105. manager.show_student(id)
  106. else:
  107. print(f"没有找到ID: {id}的学生")
  108. elif option == "3":
  109. id = input("请输入要删除的学生ID: ")
  110. manager.delete_student(id)
  111. elif option == "4":
  112. while True:
  113. id = input("请输入要更新信息的学生ID: ")
  114. try:
  115. new_info = input("请输入完整的新信息,格式:姓名 年龄 英语成绩 python成绩 c语言成绩:\n").split(" ")
  116. manager.update_student(id, new_info)
  117. except:
  118. print("您的输入有误,请重新输入。")
  119. else:
  120. break
  121. elif option == "5":
  122. manager.sort_students()
  123. elif option == "6":
  124. count = manager.count_students()
  125. print(f"学生总数:{count}")
  126. elif option == "7":
  127. manager.show_all_students()
  128. elif option == "0":
  129. print("Exiting the system...")
  130. break
  131. else:
  132. print("请输入正确的选项!")
  133. if __name__ == '__main__':
  134. main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/808101
推荐阅读
相关标签
  

闽ICP备14008679号