python编写一个简单的课时记录系统

时间:2024-04-22 18:37:43

????发现宝藏

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。

使用Python创建一个简单的课时记录系统

在学习过程中,跟踪课时的进度是非常重要的。为了方便记录和管理课时信息,我们可以使用Python编写一个简单的课时记录系统。这个系统将允许用户添加新的课程、记录已完成的课时,以及查看已完成课时的统计信息。

功能概述

  1. 添加新的课程
  2. 记录已完成的课时
  3. 查看已完成课时的统计信息

实现步骤

步骤一:创建课程类

首先,我们需要创建一个课程类来表示课程对象。每个课程将包含名称和总课时数。

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"))

实现进阶功能

1. 保存和加载课程数据

我们可以将课程数据保存到文件中,以便下次程序运行时加载已保存的课程信息。

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)
2. 用户界面改进

添加一个简单的用户界面,使用户可以更直观地与系统交互。

def main():
    tracker = CourseTracker()
    tracker.load_data("courses_data.pkl")  # 加载已保存的课程数据

    while True:
        print("\nWelcome 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()
3. 统计课程完成情况

添加一个功能,统计所有课程的完成情况,显示已完成的课时数和剩余课时数。

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")
4. 添加异常处理

为了提高系统的健壮性,我们可以添加一些异常处理机制,处理用户可能输入的错误信息。

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("\nWelcome 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()
5. 用户友好的界面优化

改进用户界面,使其更加友好和直观。

def display_menu():
    print("\nWelcome 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("\nAdd 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("\nRecord 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("\nView 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()
6. 添加删除课程功能

允许用户删除已添加的课程。

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("\nDelete Course")
    name = input("Enter course name to delete: ")
    tracker.delete_course(name)
7. 添加提醒功能

为了帮助用户更好地管理学习进度,我们可以添加一个提醒功能,当课程的剩余课时少于设定阈值时,系统会提醒用户。

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("\nSet 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.")
8. 多用户支持

允许多个用户使用系统,每个用户有独立的课程记录。

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("\nAdd User")
    username = input("Enter username: ")
    tracker.add_user(username)
    print(f"User '{username}' added successfully!")

def add_course_menu(tracker):
    print("\nAdd 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语言进行项目开发,并且可以在实际应用中体会到编程的乐趣和价值。希望本文能够对读者有所帮助,激发大家对编程和技术的兴趣,不断探索和创新。