当前位置: 首页 > news >正文

20251213 实验二《Python程序设计》实验报告

学号 2025-2026-2 《Python程序设计》实验x报告

课程:《Python程序设计》
班级: 2512
姓名: 吴同心
学号:20251213
实验教师:王志强
实验日期:2026年4月13日
必修/选修: 公选课

1.实验内容

(1)编写计算器程序
• 设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
• 考核基本语法、判定语句、循环语句、逻辑运算等知识点。
(2)用LLM生成一个计算器程序 
• 介绍相关功能,并分析生成的程序代码含义。
• 对比分析自写程序与生成程序的区别(好与坏)。

2. 实验过程及结果

(1)仿照老师演示的代码自己写了一个功能较多的计算器
代码如下:
import math

def add(a,b):
return a+b
def diff(a,b):
return a-b
def prod(a,b):
return ab
def mod(a,b):
return a%b
def div(a,b):
return a/b
def quot(a,b):
return a//b
def log(a,b):
return math.log(a,b)
def pow(a,b):
return a**b
print("神秘计算器:\n")
choice =True
while choice:
a=eval(input("请输入一个数字\n"))
b=eval(input("请输入另一个数字\n"))
operator=input("请选择运算符:+、-、
、%、/、//、log、\n")
while True:
if operator not in ["+","-","*","%","/","//","log","
"]:
print("输入的操作符有误!\n")
operator=input("请选择运算符:+、-、、%、/、//、log、**\n")
else: break
if operator"+":
print(f"{a}{operator}{b}=",add(a,b))
elif operator
"-":
print(f"{a}{operator}{b}=",diff(a, b))
elif operator=="
":
print(f"{a}{operator}{b}=",prod(a, b))
elif operator"%":
print(f"{a}{operator}{b}=",mod(a, b))
elif operator
"/":
print(f"{a}{operator}{b}=",div(a, b))
elif operator"//":
print(f"{a}{operator}{b}=",quot(a, b))
elif operator
"log":
print(f"{a}{operator}{b}=",log(a, b))
elif operator"^":
print(f"{a}{operator}{b}=",pow(a, b))
con = input("是否要继续?Y or N/n\n")
if con.lower()
"n":
choice =False
演示结果:
image

(2)利用豆包生成计算机程序完整体:
代码及注释:
import tkinter as tk
from tkinter import font

class PhoneCalculator:
def init(self, root):
self.root = root
self.root.title("手机计算器")
self.root.geometry("375x600") # 模拟手机竖屏尺寸
self.root.resizable(False, False)
self.root.configure(bg="#f5f5f5")

    # 自定义字体self.num_font = font.Font(family="Arial", size=36, weight="bold")self.op_font = font.Font(family="Arial", size=28)# 变量存储self.current_input = ""self.display_text = tk.StringVar()self.display_text.set("0")# 创建界面self._create_widgets()def _create_widgets(self):# 1. 显示屏幕区域frame_display = tk.Frame(self.root, bg="#f5f5f5", height=150)frame_display.pack(fill="both", padx=20, pady=(20, 10))frame_display.pack_propagate(False)# 显示标签 (靠右对齐)self.display_label = tk.Label(frame_display,textvariable=self.display_text,font=self.num_font,fg="#212121",bg="#f5f5f5",anchor="se",justify="right")self.display_label.pack(fill="both", expand=True)# 2. 按钮区域 (Grid布局模拟手机键盘)frame_buttons = tk.Frame(self.root, bg="#f5f5f5")frame_buttons.pack(fill="both", expand=True, padx=10, pady=10)# 按钮配置buttons = [['C', '±', '%', '÷'],['7', '8', '9', '×'],['4', '5', '6', '-'],['1', '2', '3', '+'],['0', '.', '=']]# 定义按钮颜色colors = {'num': {'bg': '#ffffff', 'fg': '#212121'},'op': {'bg': '#ff9f0a', 'fg': '#ffffff'},'func': {'bg': '#e0e0e0', 'fg': '#212121'}}# 生成按钮for row_idx, row in enumerate(buttons):for col_idx, text in enumerate(row):# 决定按钮样式if text in ['C', '±', '%']:style = colors['func']elif text in ['÷', '×', '-', '+', '=']:style = colors['op']else: # 0-9 和 .style = colors['num']# 特殊处理 0 号按钮,使其占两列colspan = 2 if text == "0" else 1btn = tk.Button(frame_buttons,text=text,font=self.op_font,width=5 if colspan == 1 else 12,height=2,relief=tk.FLAT,bd=0,**style)# 绑定点击事件btn.config(command=lambda t=text: self.on_button_click(t))btn.grid(row=row_idx,column=col_idx,columnspan=colspan,padx=8,pady=8,sticky="nsew")# 配置网格权重,让按钮自动拉伸for i in range(4):frame_buttons.grid_rowconfigure(i, weight=1)for i in range(4):frame_buttons.grid_columnconfigure(i, weight=1)def on_button_click(self, text):"""处理按钮点击逻辑"""try:if text.isdigit() or text == '.':# 处理数字和小数点if text == '.' and '.' in self.current_input:return # 避免多个小数点self.current_input += textself.display_text.set(self.current_input)elif text == 'C':# 清零self.current_input = ""self.display_text.set("0")elif text == '±':# 正负号切换if self.current_input.startswith('-'):self.current_input = self.current_input[1:]elif self.current_input:self.current_input = '-' + self.current_inputself.display_text.set(self.current_input)elif text == '%':if self.current_input:val = float(self.current_input) / 100 # 转化为百分比self.current_input = str(val)self.display_text.set(self.current_input)elif text == '=':# 计算结果 (替换 × 为 * ,÷ 为 / 以适配Python语法)expression = self.current_input.replace('×', '*').replace('÷', '/')try:result = eval(expression, {"__builtins__": None}, {})self.current_input = str(result)self.display_text.set(self.current_input)except (SyntaxError, ZeroDivisionError):self.display_text.set("错误")     #检验是否会出错self.current_input = ""else: # 运算符 (+ - × ÷)# 如果输入为空且是减号,允许输入负数if text == '-' and not self.current_input:self.current_input += textself.display_text.set(self.current_input)elif self.current_input and self.current_input[-1] in '+-×÷':# 替换最后一个运算符self.current_input = self.current_input[:-1] + textself.display_text.set(self.current_input)elif self.current_input: # 正常追加运算符self.current_input += textself.display_text.set(self.current_input)except Exception as e:self.display_text.set("错误")#防止出错self.current_input = ""

if name == "main":
root = tk.Tk()
app = PhoneCalculator(root)
root.mainloop()

功能:可以像在手机上操作一样进行多个数连续运算,而不是每两个数一点一点计算,方便快速得出答案
功能涵盖加减乘除和求余数
并且具备基本的报错检查功能,防止程序出错【看】

运行结果:
image

(3)对比分析:
①豆包生成的代码功能较为全面,可以自由清除,多个数连续运算,且界面简洁易读,健壮性强
而我写的较为简略,功能少,而且没有对非法输入进行检查(如除数为零会报错等)
②豆包生成的代码稍微有点冗余,命名长,不易阅读
我写的简单好抄,便于阅读

(4)代码托管到码云:
image

3. 实验过程中遇到的问题和解决过程

  • 问题1:编写代码被pycharm发出黄色警告
  • 问题1解决方案:换函数名,避免歧义

其他(感悟、思考等)

对python理解更进一步,也发现了自身的许多不足,对细枝末节把握不够准确

参考资料

  • 《Java程序设计与数据结构教程(第二版)》

  • 《Java程序设计与数据结构教程(第二版)》学习指导

  • ...

http://www.jsqmd.com/news/636336/

相关文章:

  • 『效率翻倍』ChatGPT Canvas快捷键全解析与实战技巧!
  • 202533122 实验二《Python程序设计》实验报告
  • GitHub 热门 | 2026年04月13日
  • Nebula Console深度解析:高效管理图数据库的核心技巧与实战指南
  • 让你的Hexo博客会唱歌:用Butterfly主题打造沉浸式音乐体验的三种高级玩法
  • 再学串串(四):后缀是后缀的后缀是后缀的后缀
  • STM32CubeMX实战|FATFS文件系统在嵌入式存储中的高效应用
  • 2026年贵州智慧停车系统与车牌识别道闸行业深度横评:五大本土企业无感通行方案对比 - 精选优质企业推荐榜
  • SpringBoot动态加载JAR包避坑指南:如何避免类冲突和内存泄漏
  • Go微服务流量治理:3个新方案解决熔断降级失效问题
  • OpenGL抗锯齿技术全解析:FXAA快速近似抗锯齿的实现与优化
  • 3步解锁B站专业直播:告别直播姬限制的终极方案
  • 4.18
  • 从检索到回答:RAG 流水线中三个被忽视的故障点
  • 浏览器中的时光机:EmulatorJS免费开源游戏模拟器终极指南
  • 手把手教你:在MounRiver Studio里为WCH RISC-V芯片切换GCC12工具链(附内存占用对比)
  • 011、AI的视觉启蒙:认识图像与像素
  • 4.19
  • 解锁JavaScript深度学习潜力:neurojs的终极未来展望与技术突破
  • 腾讯云人脸检测API签名报错?5分钟搞定Python调用避坑指南
  • 别再混淆了!PO、VO、BO、DTO、DAO、POJO 一文彻底搞懂(基于 Go 语言)
  • 终极Carnac源码解析:WPF MVVM模式在键盘监控工具中的完美实践
  • 基于vue的在线装饰城资源共享平台[vue]-计算机毕业设计源码+LW文档
  • 4.20
  • 前端首屏性能优化:5个实战方案将加载速度提至1.2s
  • 如何快速掌握Apache Shiro:探索Subject、SecurityManager和Session核心组件
  • 2026届毕业生推荐的六大降重复率平台横评
  • UE5开发避坑指南:AirSim插件Eigen头文件引用报错解决方案(附完整路径配置)
  • IoT-Technical-Guide:物联网平台API限流与防护策略终极指南
  • 终极指南:Ardour高级路由配置,构建专业音频处理系统的完整方案