20243405 2025-2026-2 《Python程序设计》实验2报告
课程:《Python程序设计》
班级: 2434
姓名: 付鸿睿
学号: 20243405
实验教师:王志强
实验日期:2026年4月13日
必修/选修: 公选课
1.实验内容
(1)编写计算器程序
设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
考核基本语法、判定语句、循环语句、逻辑运算等知识点。
(2)用LLM生成一个计算器程序
介绍相关功能,并分析生成的程序代码含义。
对比分析自写程序与生成程序的区别(好与坏)。
2.实验过程及结果
2.1 实验准备
本次实验使用Python 3.9版本和PyCharm工具,创建工程项目“Calculator_Experiment”,新建主程序文件zf.py,重点运用已学的list(可变序列)和tuple(不可变序列)知识点,完成程序编写和调试,最后将代码托管到码云。
2.2 自写计算器程序
自写程序具体代码如下:
print(" 计算器")
1.operators = ('+', '-', '', '/', '%')
2.print(f"可运算:{operators}(加、减、乘、除、取模)")
3.print("输入'q'可退出程序")
4.history = []
5.
6.while True:
7. num1_input = input("请输入第一个数字:")
8. if num1_input.lower() == 'q':
9. print("程序已退出,感谢使用!")
10. if history:
11. print("本次运算历史:")
12. for i in range(len(history)):
13. print(f"{i + 1}. {history[i]}")
14. break
15.
16. try:
17. num1 = float(num1_input)
18. except ValueError:
19. print("输入错误!请输入有效的数字(整数或小数)。")
20. continue
21.
22. operator = input(f"请输入运算符号(只能是{operators}):")
23. if operator not in operators:
24. print("运算符号错误!请重新输入。")
25. continue
26.
27. num2_input = input("请输入第二个数字:")
28. if num2_input.lower() == 'q':
29. print("程序已退出,感谢使用!")
30. if history:
31. print("本次运算历史:")
32. for i in range(len(history)):
33. print(f"{i + 1}. {history[i]}")
34. break
35.
36. try:
37. num2 = float(num2_input)
38. except ValueError:
39. print("输入错误!请输入有效的数字(整数或小数)。")
40. continue
41.
42. result = 0
43. if operator == '+':
44. result = num1 + num2
45. elif operator == '-':
46. result = num1 - num2
47. elif operator == '':
48. result = num1 * num2
49. elif operator == '/':
50. if num2 == 0:
51. print("错误!除数不能为0,请重新输入。")
52. continue
53. result = num1 / num2
54. elif operator == '%':
55. if num2 == 0:
56. print("错误!除数不能为0,请重新输入。")
57. continue
58. result = num1 % num2
59.
60. result_str = f"{num1} {operator} {num2} = {round(result, 2)}"
61. print(result_str)
62. history.append(result_str)
63.
64. continue_flag = input("是否继续运算?(y/n):")
65. if continue_flag.lower() != 'y':
66. print("程序已退出,感谢使用!")
67. if history:
68. print("本次运算历史:")
69. for i in range(len(history)):
70. print(f"{i + 1}. {history[i]}")
71. break
运行结果:程序可正常启动,输入有效数字和运算符号后,能正确输出运算结果;输入错误时会给出提示,可正常退出程序并输出运算历史,无报错,调试运行成功。
2.3 LLM生成计算器程序
用LLM生成计算器程序,提示词为“用Python编写计算器,只运用list、tuple序列知识点,实现加减乘除、取模运算,无复杂语法,逻辑简单”,生成的代码如下:
"""简易计算器程序 - 支持加减乘除和取模运算"""
print("=" * 30)
print(" 简易计算器")
print("=" * 30)
OPERATORS = {'+': '加', '-': '减', '*': '乘', '/': '除', '%': '取模'}
print(f"支持运算:{' '.join([f'{op}({name})' for op, name in OPERATORS.items()])}")
print("提示:输入 'q' 退出程序,输入 'h' 查看历史记录")
print("-" * 30)
history = []
def get_number(prompt):
"""获取用户输入的数字,支持退出功能"""
user_input = input(prompt)
if user_input.lower() == 'q':
return None, True # None表示退出
if user_input.lower() == 'h':
return None, False # None表示查看历史
try:
return float(user_input), False
except ValueError:
print("❌ 输入错误!请输入有效的数字(整数或小数)。")
return None, False
def show_history():
"""显示计算历史"""
if not history:
print("📋 暂无计算历史")
else:
print("\n" + "=" * 30)
print(" 计算历史记录")
print("=" * 30)
for i, record in enumerate(history, 1):
print(f" {i}. {record}")
print("-" * 30)
def calculate(num1, num2, operator):
"""执行计算,返回结果和错误信息"""
if operator == '+':
return num1 + num2, None
elif operator == '-':
return num1 - num2, None
elif operator == '*':
return num1 * num2, None
elif operator == '/':
if num2 == 0:
return None, "除数不能为0!"
return num1 / num2, None
elif operator == '%':
if num2 == 0:
return None, "除数不能为0!"
return num1 % num2, None
return None, "未知运算符"
def main():
"""主程序循环"""
while True:
# 获取第一个数字
num1, should_exit = get_number("请输入第一个数字:")
if should_exit:
break
if num1 is None: # 查看历史
show_history()
continue
# 获取运算符operator = input(f"请输入运算符号({''.join(OPERATORS.keys())}):")if operator.lower() == 'q':breakif operator.lower() == 'h':show_history()continueif operator not in OPERATORS:print(f"❌ 运算符号错误!支持:{' '.join(OPERATORS.keys())}")continue# 获取第二个数字num2, should_exit = get_number("请输入第二个数字:")if should_exit:breakif num2 is None: # 查看历史show_history()continue# 执行计算result, error = calculate(num1, num2, operator)if error:print(f"❌ 错误!{error}")continue# 显示结果result_str = f"{num1} {operator} {num2} = {round(result, 2)}"print(f"\n✅ 计算结果:{result_str}\n")history.append(result_str)# 询问是否继续while True:choice = input("是否继续运算?(y=继续 / n=退出 / h=查看历史):").lower()if choice == 'n' or choice == 'q':print("\n👋 程序已退出,感谢使用!")show_history()returnelif choice == 'h':show_history()elif choice == 'y':print("-" * 30)breakelse:print("❌ 输入无效!请输入 y、n 或 h")
运行结果:生成的程序可正常运行,能正确执行运算、存储运算历史,输入错误时会给出提示,无报错,调试运行成功。
2.4 自写程序与LLM生成程序对比
序列运用:
自写程序 用tuple(不可变序列)存储运算符号,list(可变序列)存储运算历史,仅运用两种序列的基础存储、添加、遍历功能;
LLM生成程序 只用list(可变序列)存储运算符号、说明和历史,运用序列的遍历、添加功能,未使用tuple
序列操作:
自写程序 运用append添加历史、range遍历序列,操作简单,贴合刚学的序列基础用法;
LLM生成程序 运用append添加历史、range遍历序列,还多了序列的对应遍历(运算符号和说明对应),操作更丰富一点
代码逻辑:
自写程序 逻辑简单,完全贴合已学知识,序列操作少而精,容易理解;
LLM生成程序 逻辑和自写程序一致,序列运用更全面,但未超出序列基础知识点
可读性:
自写程序 简单易懂,序列操作直观,适合刚学到序列的水平;
LLM生成程序 序列运用稍多,但逻辑不复杂,能快速看懂
2.5 代码托管结果
https://gitee.com/sdjxiw/pyc
3.实验过程中遇到的问题和解决过程
问题1:编写程序时,不知道如何用序列存储运算历史。
问题1解决方案:回忆课堂所学知识知识,耐心研究。
问题2:遍历序列输出运算历史时,不知道如何获取序列中的每个元素。
问题2解决方案:查阅课堂笔记,并询问同学。
其他(感悟、思考等)
不会的问ai或者老师
