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


    app.py

    1. import flask
    2. from flask import Flask, render_template, request
    3. # 计算精确的浮点结果,float加法也计算不出来
    4. from decimal import Decimal
    5. app = Flask(__name__)
    6. @app.route('/')
    7. def home():
    8. return render_template('index.html')
    9. @app.route('/calculate', methods=['POST'])
    10. # POST请求处理用户提交的数据
    11. def calculate():
    12. num1 = Decimal(request.form['num1'])
    13. num2 = Decimal(request.form['num2'])
    14. operation = request.form['operation']
    15. result = Decimal(0)
    16. # 输入的两个数和运算符,结果初始为0
    17. if operation == 'add':
    18. result = num1 + num2
    19. # 加
    20. elif operation == 'subtract':
    21. result = num1 - num2
    22. # 减
    23. elif operation == 'multiply':
    24. result = num1 * num2
    25. # 乘
    26. elif operation == 'divide':
    27. if num2 != Decimal(0):
    28. result = num1 / num2
    29. else:
    30. return "错误:分母不能为0"
    31. # 除
    32. result = round(result,4)
    33. # 保留四位小数
    34. return render_template('result.html', num1=num1, num2=num2, operation=operation, result=result)
    35. # 然后将计算结果和输入的两个参数返回给result.html渲染
    36. if __name__ == '__main__':
    37. app.run(debug=True)

    templates文件夹

    index.html

    1. html>
    2. <html>
    3. <head>
    4. <title>在线计算器title>
    5. head>
    6. <body>
    7. <h1>在线计算器h1>
    8. <form action="/calculate" method="POST">
    9. <input type="text" name="num1" required>
    10. <select name="operation" required>
    11. <option value="add">+option>
    12. <option value="subtract">-option>
    13. <option value="multiply">*option>
    14. <option value="divide">/option>
    15. select>
    16. <input type="text" name="num2" required>
    17. <button type="submit">开始计算button>
    18. form>
    19. body>
    20. html>

    result.html

    1. html>
    2. <html>
    3. <head>
    4. <title>计算结果title>
    5. head>
    6. <body>
    7. <h1>计算结果h1>
    8. <p>{{ num1 }} {{ operation }} {{ num2 }} = {{ result }}p>
    9. body>
    10. html>

    实现效果

    支持小数点计算

  • 相关阅读:
    单链表的建立(头插法、尾插法)(数据结构与算法)
    PTA题目 阶梯电价
    列式存储?OLAP?ClickHouse究竟是何方神圣
    5个不常提及的HTML技巧
    网络安全(黑客)自学
    Java8 时间处理
    MyBatis执行SQL的两种方式
    挑战100天 AI In LeetCode Day08(热题+面试经典150题)
    Java并发基石—CAS原理实战
    Oracle-truncate误删数据恢复
  • 原文地址:https://blog.csdn.net/weixin_56463218/article/details/132852074