20241305 实验二《Python程序设计》实验报告
课程:《Python程序设计》
班级: 2413
姓名: 姚航
学号:20241305
实验教师:王志强
实验日期:2026年4月13日
必修/选修: 公选课
1.实验内容
(1)编写计算器程序
设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
考核基本语法、判定语句、循环语句、逻辑运算等知识点。
(2)用LLM生成一个计算器程序
介绍相关功能,并分析生成的程序代码含义。
对比分析自写程序与生成程序的区别(好与坏)。
2. 实验过程及结果
(1)我的代码部分
首先是导入math库,然后把这些个运算函数先写好(这里我考虑到除法、求余、求商部分的b不能为0,加强一下健壮性)
import math
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def multi(a,b):
return a*b
def div(a,b):
if b==0:
return 0
else:
return a/b
def mod(a,b):
return math.fmod(a,b)
def quotient(a,b):
if b==0:
return 0
else:
return a//b
def log(a,b):
return math.log(a,b)
然后就进入计算器环节:
输入 a、b(用eval转数字,一行代码搞定数字转换,不用写 int () /float (),挺万能的这个求值的eval)
输入运算符,然后判断运算符是否合法(也就是看看和我调用的那些运算函数有能对上的吗)
合法 → 根据符号调用对应函数 → 输出结果
不合法 → 提示错误
上面两种情况过后,询问是否继续(输入Y/y都能继续,输入别的就不继续 → 退出循环)
print("欢迎使用DKY版本的计算器v1.0!\n")
while True:
a = eval(input("请输入一个数:\n"))
b = eval(input("请输入一个数:\n"))
operator = input("选择运算符号:+、-、*、/、%、//、log\n")
true_operators = ['+', '-', '*', '/', '%', '//', 'log']
if operator not in true_operators:
print("运算符输入错误!")
else:
result=0
if operator == '+':
result = sum(a, b)
elif operator == '-':
result = sub(a, b)
elif operator == '*':
result = multi(a, b)
elif operator == '/':
result = div(a, b)
elif operator == '%':
result = mod(a, b)
elif operator == '//':
result=quotient(a, b)
elif operator == 'log':
result=log(a,b)
print("结果:",result)
choice = input("是否继续计算?(y/n): ")
if choice != 'y' and choice != 'Y':
print("感谢使用计算器!")
break
我的计算器部分运行结果

(2)LLM计算器代码
它也得先导入数学库,然后用了许多颜色帮助美化,功能更全了,分两类运算,像平方、立方、根号、阶乘、sin、cos、tan只需一个数运算就行。加减乘除、指数、取余、整除这些需要两个数。安全检查这方面做的也很周全,总体生成的还不错吧。
import math
class Color:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
BOLD = '\033[1m'
END = '\033[0m'
history = []
def calculator():
print(Color.BOLD + Color.CYAN + "="*60)
print("🔥 超严谨多功能计算器(支持小数/负数/防错) 🔥")
print("="*60 + Color.END)
while True:
print("\n" + Color.GREEN + "【功能菜单】" + Color.END)
print("1.加法 2.减法 3.乘法 4.除法")
print("5.平方 6.立方 7.根号 8.阶乘")
print("9.sin 10.cos 11.tan 12.自然对数ln")
print("13.指数a^b 14.取余% 15.查看历史 16.清空历史")
print(Color.RED + "0.退出" + Color.END)
try:
choice = input("\n请输入编号:").strip()
if choice == "0":
print(Color.YELLOW + "👋 再见!" + Color.END)
break
# 单目运算
if choice in {'5','6','7','8','9','10','11','12'}:
num_str = input("请输入数字:").strip()
num = float(num_str)
if choice == '5':
res = num ** 2
expr = f"{num}² = {res}"
elif choice == '6':
res = num ** 3
expr = f"{num}³ = {res}"
elif choice == '7':
if num < 0:
print(Color.RED + "❌ 根号内不能为负数!" + Color.END)
continue
res = math.sqrt(num)
expr = f"√{num} = {res}"
elif choice == '8':
if not num.is_integer() or num < 0:
print(Color.RED + "❌ 阶乘只能是非负整数!" + Color.END)
continue
res = math.factorial(int(num))
expr = f"{int(num)}! = {res}"
elif choice == '9':
rad = math.radians(num)
res = math.sin(rad)
expr = f"sin({num}°) = {res}"
elif choice == '10':
rad = math.radians(num)
res = math.cos(rad)
expr = f"cos({num}°) = {res}"
elif choice == '11':
rad = math.radians(num)
res = math.tan(rad)
expr = f"tan({num}°) = {res}"
elif choice == '12':
if num <= 0:
print(Color.RED + "❌ 对数必须大于0!" + Color.END)
continue
res = math.log(num)
expr = f"ln({num}) = {res}"
history.append(expr)
print(f"\n✅ 结果:{Color.PURPLE}{res:.8g}{Color.END}")
# 双目运算
elif choice in {'1','2','3','4','13','14'}:
a = float(input("第一个数 a = ").strip())
b = float(input("第二个数 b = ").strip())
if choice == '1':
res = a + b
expr = f"{a} + {b} = {res}"
elif choice == '2':
res = a - b
expr = f"{a} - {b} = {res}"
elif choice == '3':
res = a * b
expr = f"{a} × {b} = {res}"
elif choice == '4':
if abs(b) < 1e-15:
print(Color.RED + "❌ 除数不能为0!" + Color.END)
continue
res = a / b
expr = f"{a} ÷ {b} = {res}"
elif choice == '13':
res = a ** b
expr = f"{a} ^ {b} = {res}"
elif choice == '14':
if abs(b) < 1e-15:
print(Color.RED + "❌ 取余模数不能为0!" + Color.END)
continue
res = a % b
expr = f"{a} % {b} = {res}"
history.append(expr)
print(f"\n✅ 结果:{Color.PURPLE}{res:.8g}{Color.END}")
elif choice == '15':
print("\n📜 历史记录:")
if not history:
print("暂无记录")
else:
for i, s in enumerate(history, 1):
print(f"{i}. {s}")
elif choice == '16':
history.clear()
print(Color.BLUE + "🧹 历史已清空" + Color.END)
else:
print(Color.RED + "❌ 无效编号" + Color.END)
except ValueError:
print(Color.RED + "❌ 输入不是有效数字!" + Color.END)
except Exception as e:
print(Color.RED + f"❌ 异常错误:{str(e)}" + Color.END)
if __name__ == "__main__":
calculator()
LLM运行截图附上

(3)比较我的代码和LLM生成代码
我的代码
优点:
简洁明了,方便理解,对新手挺友好。
实用性可以,支持小数和负数的运算。
缺点:
对数忘记作合法性的判断(这条是AI告诉我的,我还真没注意到)。
输入文字等内容,程序会崩溃。
界面太朴素,不够美观,还有优化空间。
LLM生成代码
优点:
所有数学运算都加了合法性判断:除 0、对数负数、根号负数都能判断了。
加了完整的异常捕获,输文字、输符号都不会闪退,会友好提示。
运算结果格式化显示,自动去掉多余的 0,看起来更清爽。
加入历史记录功能,能看之前算过的式子,实用性更强。
缺点:
不能处理表达式(比如输入了1+2*3这个整体作为一个数,我的代码可以让它和别的数计算,LLM代码就不行,eval确实挺万能的)。
保存历史记录的操作,只是单次运行时候有效,关闭程序下次运行就没有之前的记录了。
(4)将代码上传至Gitee
计算器原版代码
计算器LLM版代码
3. 实验过程中遇到的问题和解决过程
- 问题1:math库的调用还不熟练,开始时候还在想怎末编写程序可以实现mod运算和对数运算之类的。
- 问题1解决方案:老师上课演示才明白,调用math库,python语言还挺友好的。
- 问题2:编写函数时程序报错,指着return a/b就说是有错误。
- 问题2解决方案:自己发现的原来是if else没对齐。
- 问题3:发现在做乘法等运算时,小数位数一多,结果是一长串数。
- 问题3解决方案:AI解释的,计算机语言读取输入的10进制数会有微小的误差,相乘后误差被放大,就出现了末尾一长串0+一个数,这是正常的,可以通过结果格式化输出来解决。
其他(感悟、思考等)
这次的计算器代码整体逻辑不难,但也让我明白python代码虽然写起来方便,但是细节也要能注意得到,比如运算的基本要求,除数不能为0等,也学到了许多新东西,比如eval求值。LLM的力量也很强大,算力比较先进,写出的代码也很高级好用,未来我要合理用AI,帮助学习进步。

浙公网安备 33010602011771号