簡介
學生時代,每入門一門語言,幾乎都會試着從一個“學生信息管理系統”入門,以此來熟悉語法基礎,這裏是python3的CMD版本的“學生信息管理系統”,請盡情魔改~
源碼
:python3學生信息管理系統-CMD版本
1.效果
1.1.錄入
1.2.查詢
1.3.修改
1.4.顯示所有
可以看到,並未對學號做任何的數據校驗,字符串即可
1.5.排序
1.6.統計學生數目
1.7.刪除
2.源碼
# _*_ coding:utf-8 _*_
import os
import re
filename = "students.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(r"\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():
'''1 錄入學生信息
'''
stdentList = [] # 保存學生信息的列表
mark = True # 是否繼續添加
while mark:
id = input("請輸入ID(如 1001):")
if not id: # ID爲空,跳出循環
break
name = input("請輸入名字:")
if not name: # 名字爲空,跳出循環
break
try:
english = int(input("請輸入英語成績:"))
python = int(input("請輸入Python成績:"))
c = int(input("請輸入C語言成績:"))
except BaseException:
print("輸入無效,不是整型數值....重新錄入信息")
continue
stdent = {"id": id, "name": name, "english": english, "python": python, "c": c} # 將輸入的學生信息保存到字典
stdentList.append(stdent) # 將學生字典添加到列表中
inputMark = input("是否繼續添加?(y/n):")
if inputMark == "y": # 繼續添加
mark = True
else: # 不繼續添加
mark = False
save(stdentList) # 將學生信息保存到文件
print("學生信息錄入完畢!!!")
# 將學生信息保存到文件
def save(student):
try:
students_txt = open(filename, "a") # 以追加模式打開
except Exception as e:
students_txt = open(filename, "w") # 文件不存在,創建文件並打開
for info in student:
students_txt.write(str(info) + "\n") # 按行存儲,添加換行符
students_txt.close() # 關閉文件
def search():
'''2 查找學生成績信息
'''
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 "": # 判斷是否按ID查
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 delete():
'''3 刪除學生成績信息
'''
mark = True # 標記是否循環
while mark:
studentId = input("請輸入要刪除的學生ID:")
if studentId is not "": # 判斷要刪除的學生是否存在
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():
'''4 修改學生成績信息
'''
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 BaseException:
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():
'''5 排序
'''
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表示升序排序
elif ascORdesc == "1": # 按降序排序
ascORdescBool = True # 標記變量,爲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():
''' 6 統計學生總數
'''
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():
''' 7 顯示所有學生信息
'''
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("暫未保存數據信息...")
# 將保存在列表中的學生信息顯示出來
def show_student(studentList):
if not studentList:
print("(o@.@o) 無數據信息 (o@.@o) \n")
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{:^12}\t{:^12}\t{:^12}\t{:^12}"
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)))
if __name__ == "__main__":
main()
3.總結
代碼比較簡單,僅僅爲了掩飾簡單的邏輯判斷和使用,很適合初學者做一遍!