Contents

Python_Note2

Beautiful landscape

Nature's Beauty

Explore the wonders of the world

命令行计算器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def calculator():
    """
    命令行计算器,支持加、减、乘、除运算
    """
    print("欢迎使用命令行计算器")
    print("支持的操作:+ (加), - (减), * (乘), / (除)")
    print("输入 'exit' 退出程序")

    while True:
        try:
            # 获取用户输入
            user_input = input("请输入表达式 (例如 2 + 3): ").strip()

            # 退出条件
            if user_input.lower() == 'exit':
                print("感谢使用计算器,再见!")
                break

            # 解析输入
            parts = user_input.split()
            if len(parts) != 3:
                print("错误:请输入有效的表达式,如 '2 + 3'")
                continue

            num1, operator, num2 = parts

            # 转换数字
            num1 = float(num1)
            num2 = float(num2)

            # 执行计算
            if operator == '+':
                result = num1 + num2
            elif operator == '-':
                result = num1 - num2
            elif operator == '*':
                result = num1 * num2
            elif operator == '/':
                if num2 == 0:
                    print("错误:除数不能为零")
                    continue
                result = num1 / num2
            else:
                print(f"错误:不支持的运算符 '{operator}'")
                continue

            # 显示结果
            print(f"结果: {result}")

        except ValueError:
            print("错误:请输入有效的数字")
        except Exception as e:
            print(f"发生错误: {e}")


if __name__ == "__main__":
    calculator()

该示例涉及到了变量、函数、条件判断和异常处理的使用

学生成绩管理系统雏形

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import json


STUDENT_FILE = "students.json"

def load_students():
    """从文件加载学生数据"""
    try:
        with open(STUDENT_FILE, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}
    except json.JSONDecodeError:
        print("警告: 数据文件损坏,将使用空数据库")
        return {}

def save_students(students):
    """保存学生数据到文件"""
    with open(STUDENT_FILE, 'w') as f:
        json.dump(students, f, indent=2)

def add_student(students):
    """添加新学生"""
    student_id = input("请输入学号: ").strip()
    if not student_id:
        print("学号不能为空!")
        return

    if student_id in students:
        print("该学号已存在!")
        return

    name = input("请输入姓名: ").strip()
    if not name:
        print("姓名不能为空!")
        return

    try:
        chinese = float(input("请输入语文成绩: "))
        math = float(input("请输入数学成绩: "))
        english = float(input("请输入英语成绩: "))
    except ValueError:
        print("成绩必须为数字!")
        return

    students[student_id] = {
        'name': name,
        'scores': {
            '语文': chinese,
            '数学': math,
            '英语': english
        },
        'total': chinese + math + english,
        'average': (chinese + math + english) / 3
    }
    save_students(students)
    print("学生信息已添加!")

def query_student(students):
    """查询学生信息"""
    student_id = input("请输入要查询的学号: ").strip()
    student = students.get(student_id)

    if student:
        print("\n学生信息:")
        print(f"学号: {student_id}")
        print(f"姓名: {student['name']}")
        print("成绩:")
        for subject, score in student['scores'].items():
            print(f"  {subject}: {score}")
        print(f"总分: {student['total']}")
        print(f"平均分: {student['average']:.2f}")
    else:
        print("未找到该学生!")

def list_students(students):
    """列出所有学生"""
    if not students:
        print("当前没有学生记录!")
        return

    print("\n学生列表:")
    print("学号\t姓名\t语文\t数学\t英语\t总分\t平均分")
    for student_id, info in students.items():
        scores = info['scores']
        print(f"{student_id}\t{info['name']}\t{scores['语文']}\t{scores['数学']}\t{scores['英语']}\t{info['total']}\t{info['average']:.2f}")

def update_student(students):
    """更新学生信息"""
    student_id = input("请输入要更新的学号: ").strip()
    if student_id not in students:
        print("未找到该学生!")
        return

    print("\n当前学生信息:")
    print(f"姓名: {students[student_id]['name']}")
    print("成绩:")
    for subject, score in students[student_id]['scores'].items():
        print(f"  {subject}: {score}")

    try:
        chinese = float(input("请输入新的语文成绩: "))
        math = float(input("请输入新的数学成绩: "))
        english = float(input("请输入新的英语成绩: "))
    except ValueError:
        print("成绩必须为数字!")
        return

    students[student_id]['scores'] = {
        '语文': chinese,
        '数学': math,
        '英语': english
    }
    students[student_id]['total'] = chinese + math + english
    students[student_id]['average'] = (chinese + math + english) / 3
    save_students(students)
    print("学生信息已更新!")

def delete_student(students):
    """删除学生"""
    student_id = input("请输入要删除的学号: ").strip()
    if student_id in students:
        del students[student_id]
        save_students(students)
        print("学生信息已删除!")
    else:
        print("未找到该学生!")

def student_management():
    """学生成绩管理系统主函数"""
    students = load_students()

    while True:
        print("\n学生成绩管理系统")
        print("1. 添加学生")
        print("2. 查询学生")
        print("3. 列出所有学生")
        print("4. 更新学生信息")
        print("5. 删除学生")
        print("6. 退出")

        choice = input("请选择操作 (1-6): ").strip()

        if choice == '1':
            add_student(students)
        elif choice == '2':
            query_student(students)
        elif choice == '3':
            list_students(students)
        elif choice == '4':
            update_student(students)
        elif choice == '5':
            delete_student(students)
        elif choice == '6':
            print("再见!")
            break
        else:
            print("无效的选择,请输入1-6之间的数字!")


if __name__ == "__main__":
    student_management()

该示例使用字典存储学生信息
通过文件操作,处理 JSON 格式文件实现数据持久化
实现了完整的 CRUD 功能(创建、读取、更新、删除)