【python&flask-1】简单实现加减乘除输入界面

app.py

python 复制代码
import flask
from flask import Flask, render_template, request
# 计算精确的浮点结果,float加法也计算不出来
from decimal import Decimal

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/calculate', methods=['POST'])
# POST请求处理用户提交的数据
def calculate():
    num1 = Decimal(request.form['num1'])
    num2 = Decimal(request.form['num2'])
    operation = request.form['operation']
    result = Decimal(0)
    # 输入的两个数和运算符,结果初始为0

    if operation == 'add':
        result = num1 + num2
        # 加
    elif operation == 'subtract':
        result = num1 - num2
        # 减
    elif operation == 'multiply':
        result = num1 * num2
        # 乘
    elif operation == 'divide':
        if num2 != Decimal(0):
            result = num1 / num2
        else:
            return "错误:分母不能为0"
        # 除
    result = round(result,4)
    # 保留四位小数

    return render_template('result.html', num1=num1, num2=num2, operation=operation, result=result)
    # 然后将计算结果和输入的两个参数返回给result.html渲染
if __name__ == '__main__':
    app.run(debug=True)

templates文件夹

index.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>在线计算器</title>
</head>
<body>
    <h1>在线计算器</h1>
    <form action="/calculate" method="POST">
        <!-- 获得请求 -->
        <input type="text" name="num1" required>
        <select name="operation" required>
            <option value="add">+</option>
            <option value="subtract">-</option>
            <option value="multiply">*</option>
            <option value="divide">/</option>
            <!-- 加减乘除的操作 -->
        </select>
        <input type="text" name="num2" required>
        <button type="submit">开始计算</button>
        <!-- 提交表单 -->
    </form>
</body>
</html>
<!-- type="number" 时,浏览器会为输入字段提供一些额外的验证和用户界面上的增强功能,
例如限制输入为数值、显示数值调节器控件等。 -->

result.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>计算结果</title>
</head>
<body>
    <h1>计算结果</h1>
    <p>{{ num1 }} {{ operation }} {{ num2 }} = {{ result }}</p>
    <!-- 执行相关的计算操作的变量 -->
</body>
</html>

实现效果

支持小数点计算

相关推荐
jason_renyu1 小时前
Playwright 入门与实操:从安装、定位、断言到自动发博客,把浏览器自动化讲明白
运维·python·自动化·前端开发·浏览器自动化·playwright·e2e测试
时间的情敌1 小时前
Three.js 后处理辉光 Bloom、告警发光效果、管线流光、着色器流动管线(ShaderMaterial)
开发语言·javascript·three.js·着色器
维克兜率天1 小时前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
Evand J1 小时前
【CIR系列2】UWB视距(LOS)与非视距(NLOS)信道冲激响应(CIR)建模与对比,MATLAB
开发语言·matlab·信号处理·nlos·cir
风落青芜1 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
向科→向总工→空间动态计系统2 小时前
机器人大脑系统
开发语言·人工智能·python·机器人
染指11102 小时前
194.DeepAgents-在DeepAgents中使用自定义沙盒环境OpenSandBox
网络·人工智能·python·langchain·deepagents
一只QAQ2 小时前
c语言八股
c语言·开发语言
wuyk5552 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法
吃我一窝jio2 小时前
字节流与字符流深度解析
java·开发语言·笔记