当前位置:
首页 > Python基础教程 >
-
如何使用python编写一个简单的课时记录系统
前言
在学习过程中,跟踪课时的进度是非常重要的。为了方便记录和管理课时信息,我们可以使用Python编写一个简单的课时记录系统。这个系统将允许用户添加新的课程、记录已完成的课时,以及查看已完成课时的统计信息。
功能概述
添加新的课程
记录已完成的课时
查看已完成课时的统计信息
实现步骤
步骤一:创建课程类
首先,我们需要创建一个课程类来表示课程对象。每个课程将包含名称和总课时数。
class Course:
def __init__(self, name, total_hours):
self.name = name
self.total_hours = total_hours
步骤二:创建课时记录系统类
然后,我们创建一个课时记录系统类,该类将管理课程列表和已完成的课时记录。
class CourseTracker:
def __init__(self):
self.courses = []
def add_course(self, course):
self.courses.append(course)
def record_hours(self, course_name, hours_completed):
for course in self.courses:
if course.name == course_name:
course.total_hours -= hours_completed
break
def get_course_status(self, course_name):
for course in self.courses:
if course.name == course_name:
return course.total_hours
步骤三:使用课时记录系统
现在,我们可以使用我们创建的课时记录系统来添加课程、记录已完成的课时和查看课程状态。
# 创建课时记录系统对象
tracker = CourseTracker()
# 添加课程
tracker.add_course(Course("Python Programming", 20))
tracker.add_course(Course("Data Science", 30))
# 记录已完成的课时
tracker.record_hours("Python Programming", 5)
tracker.record_hours("Data Science", 10)
# 查看课程状态
print("Python Programming Course Hours Left:", tracker.get_course_status("Python Programming"))
print("Data Science Course Hours Left:", tracker.get_course_status("Data Science"))
实现进阶功能
-
保存和加载课程数据
我们可以将课程数据保存到文件中,以便下次程序运行时加载已保存的课程信息。
import pickle
class CourseTracker:
def __init__(self):
self.courses = []
def add_course(self, course):
self.courses.append(course)
def record_hours(self, course_name, hours_completed):
for course in self.courses:
if course.name == course_name:
course.total_hours -= hours_completed
break
def get_course_status(self, course_name):
for course in self.courses:
if course.name == course_name:
return course.total_hours
def save_data(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self.courses, f)
def load_data(self, filename):
with open(filename, 'rb') as f:
self.courses = pickle.load(f)
-
用户界面改进
添加一个简单的用户界面,使用户可以更直观地与系统交互。
def main():
tracker = CourseTracker()
tracker.load_data("courses_data.pkl") # 加载已保存的课程数据
while True:
print("
Welcome to Course Tracker System")
print("1. Add Course")
print("2. Record Hours")
print("3. View Course Status")
print("4. Save and Exit")
choice = input("Enter your choice: ")
if choice == "1":
name = input("Enter course name: ")
hours = int(input("Enter total hours: "))
tracker.add_course(Course(name, hours))
print("Course added successfully!")
elif choice == "2":
name = input("Enter course name: ")
hours_completed = int(input("Enter hours completed: "))
tracker.record_hours(name, hours_completed)
print("Hours recorded successfully!")
elif choice == "3":
name = input("Enter course name: ")
hours_left = tracker.get_course_status(name)
print(f"Hours left for {name}: {hours_left}")
elif choice == "4":
tracker.save_data("courses_data.pkl") # 保存课程数据
print("Data saved. Exiting...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
-
统计课程完成情况
添加一个功能,统计所有课程的完成情况,显示已完成的课时数和剩余课时数。
class CourseTracker:
def __init__(self):
self.courses = []
def add_course(self, course):
self.courses.append(course)
def record_hours(self, course_name, hours_completed):
for course in self.courses:
if course.name == course_name:
course.total_hours -= hours_completed
break
def get_course_status(self, course_name):
for course in self.courses:
if course.name == course_name:
return course.total_hours
def save_data(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self.courses, f)
def load_data(self, filename):
with open(filename, 'rb') as f:
self.courses = pickle.load(f)
def get_overall_status(self):
print("Overall Course Status:")
for course in self.courses:
print(f"{course.name}: Completed {course.total_hours} hours, Remaining {course.total_hours} hours")
-
添加异常处理
为了提高系统的健壮性,我们可以添加一些异常处理机制,处理用户可能输入的错误信息。
def main():
tracker = CourseTracker()
try:
tracker.load_data("courses_data.pkl") # 加载已保存的课程数据
except FileNotFoundError:
print("No existing data found. Starting with an empty course list.")
while True:
print("
Welcome to Course Tracker System")
print("1. Add Course")
print("2. Record Hours")
print("3. View Course Status")
print("4. View Overall Status")
print("5. Save and Exit")
choice = input("Enter your choice: ")
if choice == "1":
try:
name = input("Enter course name: ")
hours = int(input("Enter total hours: "))
tracker.add_course(Course(name, hours))
print("Course added successfully!")
except ValueError:
print("Invalid input! Please enter a valid number for total hours.")
elif choice == "2":
name = input("Enter course name: ")
try:
hours_completed = int(input("Enter hours completed: "))
tracker.record_hours(name, hours_completed)
print("Hours recorded successfully!")
except ValueError:
print("Invalid input! Please enter a valid number for hours completed.")
elif choice == "3":
name = input("Enter course name: ")
hours_left = tracker.get_course_status(name)
if hours_left is not None:
print(f"Hours left for {name}: {hours_left}")
else:
print("Course not found!")
elif choice == "4":
tracker.get_overall_status()
elif choice == "5":
tracker.save_data("courses_data.pkl") # 保存课程数据
print("Data saved. Exiting...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
-
用户友好的界面优化
改进用户界面,使其更加友好和直观。
def display_menu():
print("
Welcome to Course Tracker System")
print("1. Add Course")
print("2. Record Hours")
print("3. View Course Status")
print("4. View Overall Status")
print("5. Save and Exit")
def main():
tracker = CourseTracker()
try:
tracker.load_data("courses_data.pkl") # 加载已保存的课程数据
except FileNotFoundError:
print("No existing data found. Starting with an empty course list.")
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == "1":
add_course_menu(tracker)
elif choice == "2":
record_hours_menu(tracker)
elif choice == "3":
view_course_status_menu(tracker)
elif choice == "4":
tracker.get_overall_status()
elif choice == "5":
tracker.save_data("courses_data.pkl") # 保存课程数据
print("Data saved. Exiting...")
break
else:
print("Invalid choice. Please try again.")
def add_course_menu(tracker):
print("
Add Course")
name = input("Enter course name: ")
while True:
try:
hours = int(input("Enter total hours: "))
break
except ValueError:
print("Invalid input! Please enter a valid number for total hours.")
tracker.add_course(Course(name, hours))
print("Course added successfully!")
def record_hours_menu(tracker):
print("
Record Hours")
name = input("Enter course name: ")
while True:
try:
hours_completed = int(input("Enter hours completed: "))
break
except ValueError:
print("Invalid input! Please enter a valid number for hours completed.")
tracker.record_hours(name, hours_completed)
print("Hours recorded successfully!")
def view_course_status_menu(tracker):
print("
View Course Status")
name = input("Enter course name: ")
hours_left = tracker.get_course_status(name)
if hours_left is not None:
print(f"Hours left for {name}: {hours_left}")
else:
print("Course not found!")
if __name__ == "__main__":
main()
-
添加删除课程功能
允许用户删除已添加的课程。
class CourseTracker:
# ... existing code ...
def delete_course(self, course_name):
for course in self.courses:
if course.name == course_name:
self.courses.remove(course)
print(f"Course '{course_name}' deleted successfully!")
break
else:
print("Course not found!")
def delete_course_menu(tracker):
print("
Delete Course")
name = input("Enter course name to delete: ")
tracker.delete_course(name)
-
添加提醒功能
为了帮助用户更好地管理学习进度,我们可以添加一个提醒功能,当课程的剩余课时少于设定阈值时,系统会提醒用户。
class CourseTracker:
# ... existing code ...
def set_reminder_threshold(self, course_name, threshold):
for course in self.courses:
if course.name == course_name:
course.reminder_threshold = threshold
print(f"Reminder threshold set for '{course_name}'")
break
else:
print("Course not found!")
def check_reminder(self):
for course in self.courses:
if course.total_hours <= course.reminder_threshold:
print(f"Reminder: '{course.name}' has {course.total_hours} hours remaining!")
def set_reminder_threshold_menu(tracker):
print("
Set Reminder Threshold")
name = input("Enter course name: ")
while True:
try:
threshold = int(input("Enter reminder threshold: "))
break
except ValueError:
print("Invalid input! Please enter a valid number for the threshold.")
tracker.set_reminder_threshold(name, threshold)
def main():
tracker = CourseTracker()
try:
tracker.load_data("courses_data.pkl") # 加载已保存的课程数据
except FileNotFoundError:
print("No existing data found. Starting with an empty course list.")
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == "1":
add_course_menu(tracker)
elif choice == "2":
record_hours_menu(tracker)
elif choice == "3":
view_course_status_menu(tracker)
elif choice == "4":
set_reminder_threshold_menu(tracker)
elif choice == "5":
tracker.get_overall_status()
elif choice == "6":
tracker.check_reminder()
elif choice == "7":
tracker.save_data("courses_data.pkl") # 保存课程数据
print("Data saved. Exiting...")
break
else:
print("Invalid choice. Please try again.")
-
多用户支持
允许多个用户使用系统,每个用户有独立的课程记录。
class CourseTracker:
def __init__(self):
self.users = {}
def add_user(self, username):
if username not in self.users:
self.users[username] = []
def add_course(self, username, course):
self.users[username].append(course)
# ... other methods ...
def add_user_menu(tracker):
print("
Add User")
username = input("Enter username: ")
tracker.add_user(username)
print(f"User '{username}' added successfully!")
def add_course_menu(tracker):
print("
Add Course")
username = input("Enter username: ")
if username not in tracker.users:
print("User not found!")
return
name = input("Enter course name: ")
while True:
try:
hours = int(input("Enter total hours: "))
break
except ValueError:
print("Invalid input! Please enter a valid number for total hours.")
tracker.add_course(username, Course(name, hours))
print("Course added successfully!")
总结
在本文中,我们使用Python创建了一个简单而实用的课时记录系统。通过这个系统,用户可以轻松地管理课程进度,记录已完成的课时,并且可以方便地查看课程状态和统计信息。我们从基本功能开始,逐步添加了一些进阶功能,如保存和加载课程数据、统计课程完成情况、友好的用户界面优化以及提醒功能和多用户支持等。这些功能的添加使得系统更加智能、灵活和实用,满足了不同用户的需求。
通过学习本文,读者不仅可以掌握Python编程语言的基本语法和面向对象编程的基本概念,还可以了解如何设计和构建一个简单但功能强大的应用程序。此外,读者还可以从中学习到如何通过不断改进和拓展来完善一个项目,以及如何处理用户可能遇到的各种情况和错误。
到此这篇关于如何使用python编写一个简单的课时记录系统的文章就介绍到这了,更多相关python课时记录系统内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/weixin_52908342/article/details/138033004
栏目列表
最新更新
python爬虫及其可视化
使用python爬取豆瓣电影短评评论内容
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比