20252415 实验二《Python程序设计》实验报告
学号 2025-2026-2 《Python程序设计》实验x报告
课程:《Python程序设计》
班级: 2524
姓名: 陈至晟
学号:20252415
实验教师:王志强
实验日期:2026年4月13日
必修/选修: 公选课
1.实验内容
(一)实验内容
(1) 编写计算器程序
- 设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
- 考核基本语法、判定语句、循环语句、逻辑运算等知识点。
(2)用LLM生成一个计算器程序 - 介绍相关功能,并分析生成的程序代码含义。
- 对比分析自写程序与生成程序的区别(好与坏)。
2. 实验过程及结果
(一)编写计算器程序
- 功能分析:
- 必须是函数形式。
- 支持整数、浮点数等数据类型。
- 能够完成加、减、乘、除、除模、平方等运算。
- 在输入完整表达式时,程序自动识别数据类型并选择算法。
- 能够识别不正确的表达式输入,并提醒用户重新输入。
- 一轮运算结束后,用户能够决定是否再次进行运算。
具体过程:
- 重点详解:
- 调用库函数:
import math #math库用来处理实数计算
- 分区编写对应函数:
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def mod(a,b):
return a%b
def quotient(a,b):
return a//b
def log(a,b):
return math.log(a,b)
def pow(a,b):
return math.pow(a,b)
3.校验操作符格式:
while True:
if operator not in ["+","-","*","/","%","//","log","pow"]:
print("操作符输入有误,请重新输入")
operator = input("选择运算符号:+、-、*、/、%、//、log,pow\n")
else :
break
4.自主选择是否继续
choice=True
while choice:
~~~~~ #见详细代码
con=input("是否要继续? Y or N\n")
con=con.lower()
if con=="y":
choice=True
else :
choice=False
- 详细代码:
# -*- coding: utf-8 -*-
# File : 计算器设计 .py
# Author : 无忆江南
# Create Time : 2026/4/13 19:01
# Python Version : 3.18.12
# " ————when it is dark enough ,we can see the stars."
import math
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def mod(a,b):
return a%b
def quotient(a,b):
return a//b
def log(a,b):
return math.log(a,b)
def pow(a,b):
return math.pow(a,b)
print("简单刺激计算器 v1.0")
choice=True
while choice:
a=eval(input("请输入一个数:\n"))
b=eval(input("请再输入一个数:\n"))
operator=input("选择运算符号:+、-、*、/、%、//、log、pow\n")
while True:
if operator not in ["+","-","*","/","%","//","log","pow"]:
print("操作符输入有误,请重新输入")
operator = input("选择运算符号:+、-、*、/、%、//、log,pow\n")
else :
break
if operator=="+":
print(f"{a}{operator}{b}=",sum(a,b))
elif operator=="-":
print(f"{a}{operator}{b}=",sub(a,b))
elif operator=="*":
print(f"{a}{operator}{b}=",mul(a,b))
elif operator=="/":
print(f"{a}{operator}{b}=",div(a,b))
elif operator=="%":
print(f"{a}{operator}{b}=",mod(a,b))
elif operator=="//":
print(f"{a}{operator}{b}=",quotient(a,b))
elif operator=="log":
print(f"{a}{operator}{b}=",log(a,b))
elif operator=="pow":
print(f"{a}{operator}{b}=",pow(a,b))
con=input("是否要继续? Y or N\n")
con=con.lower()
if con=="y":
choice=True
else :
choice=False
- 本地运行结果:
简单刺激计算器 v1.0
请输入一个数:
5
请再输入一个数:
6
选择运算符号:+、-、*、/、%、//、log、pow
/
5/6= 0.8333333333333334
是否要继续? Y or N
y
请输入一个数:
3
请再输入一个数:
9
选择运算符号:+、-、*、/、%、//、log、pow
*
3*9= 27
是否要继续? Y or N
n
进程已结束,退出代码为 0
(二)用LLM生成一个计算器程序
- 代码见下:
# -*- coding: utf-8 -*-
# File : 计算器(豆包版本) .py
# Author : 无忆江南
# Create Time : 2026/4/13 21:09
# Python Version : 3.18.12
# " ————when it is dark enough ,we can see the stars."
import math
def calculate(expr):
"""计算表达式,带安全替换与异常处理"""
try:
# 安全替换关键字
expr = expr.replace("pi", str(math.pi))
expr = expr.replace("π", str(math.pi))
expr = expr.replace("e", str(math.e))
expr = expr.replace("^", "**")
expr = expr.replace("sqrt", "math.sqrt")
expr = expr.replace("sin", "math.sin")
expr = expr.replace("cos", "math.cos")
expr = expr.replace("tan", "math.tan")
expr = expr.replace("log", "math.log10")
expr = expr.replace("fact", "math.factorial")
expr = expr.replace("deg2rad", "math.radians")
# 角度制三角函数适配(自动转弧度)
import re
expr = re.sub(r'sin\((.*?)\)', r'sin(deg2rad(\1))', expr)
expr = re.sub(r'cos\((.*?)\)', r'cos(deg2rad(\1))', expr)
expr = re.sub(r'tan\((.*?)\)', r'tan(deg2rad(\1))', expr)
# 安全计算
result = eval(expr)
return round(result, 12)
except ZeroDivisionError:
return "❌ 错误:除数不能为0"
except SyntaxError:
return "❌ 错误:表达式格式不正确"
except ValueError:
return "❌ 错误:数学运算无效(如负数开方)"
except NameError:
return "❌ 错误:输入了不支持的函数"
except Exception as e:
return f"❌ 错误:{str(e)}"
def show_help():
"""显示帮助菜单"""
print("""
╭─────────────────────────────────────╮
│ 🧮 命令行计算器 │
│ 支持:+ - * / % ^ sqrt sin cos tan │
│ fact(阶乘) log(10底) π e │
│ 示例: │
│ 1+2*3-sqrt(16) │
│ sin(90)+cos(0)+fact(5) │
│ π*2^2 │
│ 输入 quit 退出,help 查看帮助 │
╰─────────────────────────────────────╯
""")
def main():
show_help()
while True:
expr = input("\n➡ 请输入表达式:").strip()
if not expr:
continue
if expr.lower() in ["quit", "exit", "q"]:
print("👋 再见!")
break
if expr.lower() == "help":
show_help()
continue
res = calculate(expr)
print(f"✅ 结果:{res}")
if __name__ == "__main__":
main()
- 功能说明
1.支持写入数学常数及相关术语
# 把文字替换成数学库能识别的内容
expr = expr.replace("pi", str(math.pi))
expr = expr.replace("π", str(math.pi))
expr = expr.replace("e", str(math.e))
expr = expr.replace("^", "**")
expr = expr.replace("sqrt", "math.sqrt")
expr = expr.replace("sin", "math.sin")
expr = expr.replace("cos", "math.cos")
expr = expr.replace("tan", "math.tan")
expr = expr.replace("log", "math.log10")
expr = expr.replace("fact", "math.factorial")
expr = expr.replace("deg2rad", "math.radians")
2.自动转换弧度
import re
expr = re.sub(r'sin\((.*?)\)', r'sin(deg2rad(\1))', expr)
expr = re.sub(r'cos\((.*?)\)', r'cos(deg2rad(\1))', expr)
expr = re.sub(r'tan\((.*?)\)', r'tan(deg2rad(\1))', expr)
3.异常处理(保证程序不崩溃)
except ZeroDivisionError:
return "❌ 错误:除数不能为0"
except SyntaxError:
return "❌ 错误:表达式格式不正确"
except ValueError:
return "❌ 错误:数学运算无效(如负数开方)"
except NameError:
return "❌ 错误:输入了不支持的函数"
except Exception as e:
return f"❌ 错误:{str(e)}"
4.显示美观的功能说明界面
def show_help():
print("""
╭─────────────────────────────────────╮
│ 🧮 命令行计算器 │
│ 支持:+ - * / % ^ sqrt sin cos tan │
│ fact(阶乘) log(10底) π e │
╰─────────────────────────────────────╯
""")
- 好与坏
1.好:
1)简单易懂;
2)函数封装规范,结构清晰。
2.坏:
1)健壮性差,没有对全部输入进行规范;
2)一次只能对两个数进行计算,无法计算连续表达式;
3)没有错误处理,如除0、log负数。
(三)配置华为云ECS弹性云服务器
1.购买公网IP
配置:
-
按需计费
-
全动态BGP
-
按流量计费
-
带宽300Mbit/s
2.购买弹性云服务器
配置:
-
按需计费
-
鲲鹏计算-kc1.small.1
-
系统镜像:openEuler 22.03 (10GiB)
-
系统盘:高IO-40GiB
-
安全组:Sys-FullAccess
-
公网IP:使用已有
3.连接云虚拟机:使用虚拟机列表界面自带的CloudShell进行访问。

4.检查python安装情况

5.使用python运行代码

(四)代码上传码云

- 仓库链接:- 计算器设计.py
3. 实验过程中遇到的问题和解决过程
- 问题1:不知道在python中如何支持负数运算;
- 问题1解决方案:在经过老师指导后知道了使用eval()定义数据
其他(感悟、思考等)
(1)一定要注意程序的健壮性;
(2)在编写与数学计算有关的程序时要注意相关法则。

浙公网安备 33010602011771号