小明:嘿,小红!我最近在学习Python,想尝试做一个学生管理信息系统。你能帮我一起完成吗?
小红:当然可以!这听起来很有趣。我们先规划一下系统的基本功能吧,比如添加学生信息、查询、修改和删除。
小明:对,还有排名功能也很重要,可以让用户查看每个学生的成绩排名。
小红:好主意!我们可以用SQLite作为数据库,Python处理逻辑。首先创建数据库表。
import sqlite3
conn = sqlite3.connect('student.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
score REAL);''')
conn.commit()
conn.close()
小明:接下来是添加学生信息的部分,我来写这部分代码。
def add_student(name, score):
conn = sqlite3.connect('student.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO students (name, score) VALUES (?, ?)", (name, score))
conn.commit()
conn.close()
# 示例调用
add_student("张三", 95)
add_student("李四", 85)
小红:现在我们需要实现排名功能。可以通过SQL查询直接获取排序结果。
def get_rank():
conn = sqlite3.connect('student.db')
cursor = conn.cursor()
cursor.execute("SELECT name, score FROM students ORDER BY score DESC")
rows = cursor.fetchall()
for i, row in enumerate(rows, start=1):
print(f"Rank {i}: {row[0]} with score {row[1]}")
conn.close()
# 调用排名函数
get_rank()
小明:这样就能看到每个学生的成绩排名了。不过,演示的时候怎么让用户更直观地看到呢?
小红:我们可以用PyQt做一个简单的GUI界面,加载数据并显示排名。
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
label = QLabel("Student Ranking System")
layout.addWidget(label)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication([])
ex = App()
ex.show()
app.exec_()
小明:太棒了!这个系统不仅实用,而且演示起来也相当直观。你觉得还有什么需要改进的地方吗?
小红:我们可以增加更多的错误处理,比如检查输入是否合法,以及优化界面布局。
本站部分内容及素材来源于互联网,由AI智能生成,如有侵权或言论不当,联系必删!