1. 程式人生 > 程式設計 >python實現簡易學生資訊管理系統

python實現簡易學生資訊管理系統

本文例項為大家分享了python實現學生資訊管理系統的具體程式碼,供大家參考,具體內容如下

簡易學生資訊管理系統主要功能有

1 錄入學生資訊
2 查詢學生資訊
3 刪除學生資訊
4 修改學生資訊
5 排序
6 統計學生總人數
7 顯示所有學生資訊
0 退出系統

系統執行效果

主選單的程式碼方法:

# Author: dry
# 開發時間:2019/9/11
# 開發工具:PyCharm
import re # 匯入正則表示式模組
import os # 匯入作業系統模組
filename = "student.txt" # 學生資訊儲存檔案
def menu():
  # 輸出選單
  print('''
   ---------------學生資訊管理系統------------
   ==================功能選單================
          1 錄入學生資訊
          2 查詢學生資訊
          3 刪除學生資訊
          4 修改學生資訊
          5 排序
          6 統計學生總人數
          7 顯示所有學生資訊
          0 退出系統
   =======================================  
         說明:通過數字選擇選單
   =======================================
  ''')

系統主方法:

def main():
  ctrl = True # 標記是否退出系統
  while (ctrl):
    menu() # 顯示選單
    option = input("請選擇:") # 選擇選單項
    option_str = re.sub("\D","",option) # 提取數字
    if option_str in ['0','1','2','3','4','5','6','7']:
      option_int = int(option_str)
      if option_int == 0: # 退出系統
        print('您已退出學生成績管理系統!')
        ctrl = False
      elif option_int == 1: # 錄入學生成績資訊
        insert()
      elif option_int == 2: # 查詢學生成績資訊
        search()
      elif option_int == 3: # 刪除學生成績資訊
        delete()
      elif option_int == 4: # 修改學生成績資訊
        modify()
      elif option_int == 5: # 排序
        sort()
      elif option_int == 6: # 統計學生總數
        total()
      elif option_int == 7: # 顯示所有學生資訊
        show()

錄入學生資訊方法:

'''錄入學生資訊'''
def insert():
  studentList = [] # 儲存學生資訊的列表
  mark = True # 是否繼續新增
  while mark:
    id = input("請輸入學生ID(如1001):")
    if not id:
      break
    name = input("請輸入名字:")
    if not name:
      break
    try:
      english = int(input("請輸入英語成績:"))
      python = int(input("請輸入python成績:"))
      c = int(input("請輸入C語言成績:"))
    except:
      print("輸入無效,不是整型數值,請重新輸入資訊")
      continue
      # 將輸入的學生資訊儲存到字典
    student = {"id": id,"name": name,"english": english,"python": python,"c": c}
    studentList.append(student) # 將學生字典新增到列表中
    inputList = input("是否繼續新增?(y/n):")
    if inputList == 'y': # 繼續新增
      mark = True
    else:
      mark = False
    save(studentList) # 將學生資訊儲存到檔案
    print("學生資訊錄入完畢!!!")

儲存學生資訊方法:

'''將學生資訊儲存到檔案'''
def save(student):
  try:
    student_txt = open(filename,'a') # 以追加模式開啟
  except Exception as e:
    student_txt = open(filename,'w') # 檔案不存在,建立檔案並開啟
  for info in student:
    student_txt.write(str(info) + "\n") # 執行儲存,新增換行符
  student_txt.close() # 關閉檔案

查詢學生資訊方法:

'''查詢學生資訊'''
def search():
  mark = True
  student_query = []
  while mark:
    id = ""
    name = ""
    if os.path.exists(filename):
      mode = input("按ID查詢輸入1:按姓名查詢輸入2:")
      if mode == "1":
        id = input("請輸入學生ID:")
      elif mode == "2":
        name = input("請輸入學生姓名:")
      else:
        print("您輸入有誤,請重新輸入!")
        search()
      with open(filename,"r") as file:
        student = file.readlines()
        for list in student:
          d = dict(eval(list))
          if id is not "":
            if d['id'] == id:
              student_query.append(d)
          elif name is not "":
            if d['name'] == name:
              student_query.append(d)
        show_student(student_query)
        student_query.clear()
        inputMark = input("是否繼續查詢?(y/n):")
        if inputMark == "y":
          mark = True
        else:
          mark = False
    else:
      print("暫未儲存資料資訊...")
      return

顯示學生資訊方法

'''將儲存在列表中的學生資訊顯示出來'''
def show_student(studentList):
  if not studentList:
    print("無效的資料")
    return
  format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:10}"
  print(format_title.format("ID","名字","英語成績","python成績","C語言成績","總成績"))
  format_data = "{:^6}{:^12}\t{:^10}\t{:^10}\t{:^10}\t{:10}"
  for info in studentList:
    print(format_data.format(info.get("id"),info.get("name"),str(info.get("english")),str(info.get("python")),str(info.get("c")),str(info.get("english") + info.get("python") + info.get("c")).center(12)))

刪除學生資訊方法:

'''刪除學生資訊'''
def delete():
  mark = True # 標記是否迴圈
  while mark:
    studentId = input("請輸入要刪除的學生ID:")
    if studentId is not "": # 判斷要刪除的學生ID是否存在
      if os.path.exists(filename):
        with open(filename,'r') as rfile:
          student_old = rfile.readlines()
      else:
        student_old = []
      ifdel = False # 標記是否刪除
      if student_old: # 如果存在學生資訊
        with open(filename,'w') as wfile:
          d = {} # 定義空字典
          for list in student_old:
            d = dict(eval(list)) # 字串轉字典
            if d['id'] != studentId:
              wfile.write(str(d) + "\n") # 將一條資訊寫入檔案
            else:
              ifdel = True # 標記已經刪除
          if ifdel:
            print("ID為%s的學生資訊已經被刪除..." % studentId)
          else:
            print("沒有找到ID為%s的學生資訊..." % studentId)
      else:
        print("不存在學生資訊")
        break
      show() # 顯示全部學生資訊
      inputMark = input("是否繼續刪除?(y/n):")
      if inputMark == "y":
        mark = True # 繼續刪除
      else:
        mark = False # 退出刪除學生資訊操作

修改學生資訊方法:

'''修改學生資訊'''
def modify():
  show() # 顯示全部學生資訊
  if os.path.exists(filename):
    with open(filename,'r') as rfile:
      student_old = rfile.readlines()
  else:
    return
  studentid = input("請輸入要修改的學生ID:")
  with open(filename,'w') as wfile:
    for student in student_old:
      d = dict(eval(student))
      if d['id'] == studentid:
        print("找到了這名學生,可以修改他的資訊")
        while True: # 輸入要修改的資訊
          try:
            d["name"] = input("請輸入姓名:")
            d["english"] = int(input("請輸入英語成績:"))
            d["python"] = int(input("請輸入python成績:"))
            d['c'] = int(input("請輸入C語言成績:"))
          except:
            print("您輸入有誤,請重新輸入!")
          else:
            break
        student = str(d) # 將字典轉為字串
        wfile.write(student + "\n") # 將修改資訊寫入到檔案
        print("修改成功")
      else:
        wfile.write(student) # 將未修改的資訊寫入檔案
  mark = input("是否繼續修改其他學生資訊?(y/n):")
  if mark == "y":
    modify()

學生資訊排序方法:

'''排序'''
def sort():
  show()
  if os.path.exists(filename):
    with open(filename,'r') as file:
      student_old = file.readlines()
      student_new = []
    for list in student_old:
      d = dict(eval(list))
      student_new.append(d)
  else:
    return
  ascORdesc = input("請選擇(0升序;1降序)")
  if ascORdesc == "0":
    ascORdescBool = False # 標記變數,為False時表示升序,為True時表示降序
  elif ascORdesc == "1":
    ascORdescBool = True
  else:
    print("您輸入的資訊有誤,請重新輸入!")
    sort()
  mode = input("請選擇排序方式(1按英語成績排序;2按python成績排序;3按C語言成績排序;0按總成績排序):")
  if mode == "1": # 按英語成績排序
    student_new.sort(key=lambda x: x["english"],reverse=ascORdescBool)
  elif mode == "2": # 按python成績排序
    student_new.sort(key=lambda x: x["python"],reverse=ascORdescBool)
  elif mode == "3": # 按C語言成績排序
    student_new.sort(key=lambda x: x["c"],reverse=ascORdescBool)
  elif mode == "0": # 按總成績排序
    student_new.sort(key=lambda x: x["english"] + x["python"] + x["c"],reverse=ascORdescBool)
  else:
    print("您的輸入有誤,請重新輸入!")
    sort()
  show_student(student_new) # 顯示排序結果

統計學生總數方法:

'''統計學生總數'''
def total():
  if os.path.exists(filename):
    with open(filename,'r') as rfile:
      student_old = rfile.readlines()
      if student_old:
        print("一共有%d名學生!" % len(student_old))
      else:
        print("還沒有錄入學生資訊")
  else:
    print("暫未儲存資料資訊")

顯示所有學生資訊方法:

'''顯示所有學生資訊'''
def show():
  student_new = []
  if os.path.exists(filename):
    with open(filename,'r') as rfile:
      student_old = rfile.readlines()
    for list in student_old:
      student_new.append(eval(list))
    if student_new:
      show_student(student_new)
    else:
      print("暫未儲存資料資訊")

開始函式:

if __name__ == '__main__':
  main()

完整程式碼如下:

# Author: dry
# 開發時間:2019/9/11
# 開發工具:PyCharm
import re # 匯入正則表示式模組
import os # 匯入作業系統模組

filename = "student.txt" # 學生資訊儲存檔案


def menu():
  # 輸出選單
  print('''
   ---------------學生資訊管理系統------------
   ==================功能選單================
          1 錄入學生資訊
          2 查詢學生資訊
          3 刪除學生資訊
          4 修改學生資訊
          5 排序
          6 統計學生總人數
          7 顯示所有學生資訊
          0 退出系統
   =======================================  
         說明:通過數字選擇選單
   =======================================
  ''')


def main():
  ctrl = True # 標記是否退出系統
  while (ctrl):
    menu() # 顯示選單
    option = input("請選擇:") # 選擇選單項
    option_str = re.sub("\D",'7']:
      option_int = int(option_str)
      if option_int == 0: # 退出系統
        print('您已退出學生成績管理系統!')
        ctrl = False
      elif option_int == 1: # 錄入學生成績資訊
        insert()
      elif option_int == 2: # 查詢學生成績資訊
        search()
      elif option_int == 3: # 刪除學生成績資訊
        delete()
      elif option_int == 4: # 修改學生成績資訊
        modify()
      elif option_int == 5: # 排序
        sort()
      elif option_int == 6: # 統計學生總數
        total()
      elif option_int == 7: # 顯示所有學生資訊
        show()


'''錄入學生資訊'''


def insert():
  studentList = [] # 儲存學生資訊的列表
  mark = True # 是否繼續新增
  while mark:
    id = input("請輸入學生ID(如1001):")
    if not id:
      break
    name = input("請輸入名字:")
    if not name:
      break
    try:
      english = int(input("請輸入英語成績:"))
      python = int(input("請輸入python成績:"))
      c = int(input("請輸入C語言成績:"))
    except:
      print("輸入無效,不是整形數值,請重新輸入資訊")
      continue
      # 將輸入的學生資訊儲存到字典
    student = {"id": id,"c": c}
    studentList.append(student) # 將學生字典新增到列表中
    inputList = input("是否繼續新增?(y/n):")
    if inputList == 'y': # 繼續新增
      mark = True
    else:
      mark = False
    save(studentList) # 將學生資訊儲存到檔案
    print("學生資訊錄入完畢!!!")


'''將學生資訊儲存到檔案'''


def save(student):
  try:
    student_txt = open(filename,'w') # 檔案不存在,建立檔案並開啟
  for info in student:
    student_txt.write(str(info) + "\n") # 執行儲存,新增換行符
  student_txt.close() # 關閉檔案


'''查詢學生資訊'''


def search():
  mark = True
  student_query = []
  while mark:
    id = ""
    name = ""
    if os.path.exists(filename):
      mode = input("按ID查詢輸入1:按姓名查詢輸入2:")
      if mode == "1":
        id = input("請輸入學生ID:")
      elif mode == "2":
        name = input("請輸入學生姓名:")
      else:
        print("您輸入有誤,請重新輸入!")
        search()
      with open(filename,"r") as file:
        student = file.readlines()
        for list in student:
          d = dict(eval(list))
          if id is not "":
            if d['id'] == id:
              student_query.append(d)
          elif name is not "":
            if d['name'] == name:
              student_query.append(d)
        show_student(student_query)
        student_query.clear()
        inputMark = input("是否繼續查詢?(y/n):")
        if inputMark == "y":
          mark = True
        else:
          mark = False
    else:
      print("暫未儲存資料資訊...")
      return


'''將儲存在列表中的學生資訊顯示出來'''


def show_student(studentList):
  if not studentList:
    print("無效的資料")
    return
  format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:10}"
  print(format_title.format("ID",str(info.get("english") + info.get("python") + info.get("c")).center(12)))


'''刪除學生資訊'''


def delete():
  mark = True # 標記是否迴圈
  while mark:
    studentId = input("請輸入要刪除的學生ID:")
    if studentId is not "": # 判斷要刪除的學生ID是否存在
      if os.path.exists(filename):
        with open(filename,'w') as wfile:
          d = {} # 定義空字典
          for list in student_old:
            d = dict(eval(list)) # 字串轉字典
            if d['id'] != studentId:
              wfile.write(str(d) + "\n") # 將一條資訊寫入檔案
            else:
              ifdel = True # 標記已經刪除
          if ifdel:
            print("ID為%s的學生資訊已經被刪除..." % studentId)
          else:
            print("沒有找到ID為%s的學生資訊..." % studentId)
      else:
        print("不存在學生資訊")
        break
      show() # 顯示全部學生資訊
      inputMark = input("是否繼續刪除?(y/n):")
      if inputMark == "y":
        mark = True # 繼續刪除
      else:
        mark = False # 退出刪除學生資訊操作


'''修改學生資訊'''


def modify():
  show() # 顯示全部學生資訊
  if os.path.exists(filename):
    with open(filename,'w') as wfile:
    for student in student_old:
      d = dict(eval(student))
      if d['id'] == studentid:
        print("找到了這名學生,可以修改他的資訊")
        while True: # 輸入要修改的資訊
          try:
            d["name"] = input("請輸入姓名:")
            d["english"] = int(input("請輸入英語成績:"))
            d["python"] = int(input("請輸入python成績:"))
            d['c'] = int(input("請輸入C語言成績:"))
          except:
            print("您輸入有誤,請重新輸入!")
          else:
            break
        student = str(d) # 將字典轉為字串
        wfile.write(student + "\n") # 將修改資訊寫入到檔案
        print("修改成功")
      else:
        wfile.write(student) # 將未修改的資訊寫入檔案
  mark = input("是否繼續修改其他學生資訊?(y/n):")
  if mark == "y":
    modify()


'''排序'''


def sort():
  show()
  if os.path.exists(filename):
    with open(filename,reverse=ascORdescBool)
  else:
    print("您的輸入有誤,請重新輸入!")
    sort()
  show_student(student_new) # 顯示排序結果


'''統計學生總數'''


def total():
  if os.path.exists(filename):
    with open(filename,'r') as rfile:
      student_old = rfile.readlines()
      if student_old:
        print("一共有%d名學生!" % len(student_old))
      else:
        print("還沒有錄入學生資訊")
  else:
    print("暫未儲存資料資訊")


'''顯示所有學生資訊'''


def show():
  student_new = []
  if os.path.exists(filename):
    with open(filename,'r') as rfile:
      student_old = rfile.readlines()
    for list in student_old:
      student_new.append(eval(list))
    if student_new:
      show_student(student_new)
    else:
      print("暫未儲存資料資訊")


if __name__ == '__main__':
  main()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。