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 1

            btn = 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 += text
            self.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_input
            self.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 += text
                self.display_text.set(self.current_input)
            elif self.current_input and self.current_input[-1] in '+-×÷':
                # 替换最后一个运算符
                self.current_input = self.current_input[:-1] + text
                self.display_text.set(self.current_input)
            elif self.current_input: # 正常追加运算符
                self.current_input += text
                self.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理解更进一步,也发现了自身的许多不足,对细枝末节把握不够准确

参考资料

posted @ 2026-04-13 22:28  Aminoas  阅读(9)  评论(0)    收藏  举报