Building a Web-Based Calculator with Flask



Here, we will learn the step-by-step process of creating a web-based calculator using Python and Flask. Flask is helpful and simple to install for Python and perfect for projects of small to medium size. For the newcomers in the field of web development using Python this tutorial is excellent way to start.

We will also review the minimum amount of html, CSS, and JavaScript that is required to build the calculator interface that will allow for simple calculations.

Installations

First, we need to make sure that we have Python and Flask installed before we proceed with the coding. If you havent installed Flask yet, you can easily install it through the pip which is pythons package installer.

Step 1: Install Python

First, you have to installed Python on your machine. You can download it from the official Python website.

Read also: Python Environment Setup

Step 2: Install Flask

Open your command prompt or terminal and run the following command −

pip install flask

Building a Web-Based Calculator with Flask

We'll start by creating a simple Flask app, followed by designing the HTML for the calculator interface and styling it with CSS.

Step 1: Creating the Flask App (app.py)

This file will store the main logic of our Flask application.

app.py Code

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
   result = ''
   if request.method == "POST":
      try:
         expression = request.form["display"]
         # Evaluate the expression safely using eval
         result = eval(expression)
      except Exception as e:
         result = "Error"
   return render_template("index.html", result=result)

if __name__ == "__main__":
   app.run(debug=True)

Code Explanation

Let us begin by importing the necessary modules, these include; Flask, RenderTemplate, and Request.

The index() function processes both of the HTTP methods protocols which include GET and POST. When the user submits the form (POST request), the function tries to calculate the expression which has been entered by the user and returns this value.

If there is any problem during the evaluation process (example, wrong input), it gives "Error".

Lastly, we make the index. HTML template with the result of the computation to be done.

Step 2: Creating the HTML Template (index.html)

Create a templates directory inside your project folder. Inside templates, create a file named index.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Calculator</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="calculator">
   <h1>Flask Calculator</h1>
   <form method="POST">
      <input type="text" name="display" id="display" value="{{ result }}" readonly>

      <div class="buttons">
         <button type="button" class="btn" onclick="appendToDisplay('1')">1</button>
         <button type="button" class="btn" onclick="appendToDisplay('2')">2</button>
         <button type="button" class="btn" onclick="appendToDisplay('3')">3</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('+')">+</button>

         <button type="button" class="btn" onclick="appendToDisplay('4')">4</button>
         <button type="button" class="btn" onclick="appendToDisplay('5')">5</button>
         <button type="button" class="btn" onclick="appendToDisplay('6')">6</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('-')">-</button>

         <button type="button" class="btn" onclick="appendToDisplay('7')">7</button>
         <button type="button" class="btn" onclick="appendToDisplay('8')">8</button>
         <button type="button" class="btn" onclick="appendToDisplay('9')">9</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('*')"></button>

         <button type="button" class="btn" onclick="appendToDisplay('0')">0</button>
         <button type="button" class="btn" onclick="clearDisplay()">C</button>
         <button type="submit" class="btn operator">=</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('/')"></button>
      </div>
   </form>
</div>

<script>
   function appendToDisplay(value) {
      const display = document.getElementById('display');
      display.value += value;
   }

   function clearDisplay() {
      document.getElementById('display').value = '';
   }
</script>
</body>
</html>

Code Explanation

The index. html file sets up how the calculator is to look. As of this program it has an input field to give the entered values and the result.

There are buttons for numbers and for math operations which include +, -, * , / and functional keys that include C button to clear the result and = button to get the result.

The buttons along the calculator; append to display and clear uses JavaScript functions to facilitate the interaction with the buttons and the display updating or clearing it.

Step 3: Adding Some Style (style.css)

Create a static directory inside your project folder. Inside static, create a file named style.css to style the calculator.

body {
   font-family: Arial, sans-serif;
   background-color: #f0f0f0;
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
   margin: 0;
}

.calculator {
   width: 100%;
   max-width: 600px;
   background-color: #333;
   padding: 30px;
   border-radius: 15px;
   box-shadow: 0px 0px 15px 0px #000;
   text-align: center;
}

h1 {
   color: #fff;
   margin-bottom: 20px;
   font-size: 36px;
}

#display {
   width: 100%;
   height: 80px;
   font-size: 36px;
   text-align: right;
   padding: 15px;
   margin-bottom: 20px;
   border-radius: 10px;
   border: none;
   background-color: #222;
   color: #fff;
}

.buttons {
   display: grid;
   grid-template-columns: repeat(4, 1fr);
   gap: 15px;
}

.btn {
   width: 100%;
   padding: 30px;
   font-size: 24px;
   border: none;
   border-radius: 10px;
   background-color: #666;
   color: #fff;
   cursor: pointer;
   transition: background-color 0.2s;
}

.btn:hover {
   background-color: #555;
}

.operator {
   background-color: #ff9500;
}

.operator:hover {
   background-color: #e68a00;
}

.btn:active {
   background-color: #444;
}

.operator:active {
   background-color: #cc7a00;
}

Step 4: Running the Application

Now that we have all the necessary files, you can run your Flask application by executing the following command in your project directory −

python app.py

Visit http://127.0.0.1:5000/ in your web browser to see your web-based calculator.

python app

Output

Now http://127.0.0.1:5000 copy this paste in incognito window.

python app

Now you will this interface

web-based calculator

Now you can use your mouse click you can do calculate

web-based calculator
python_projects_from_basic_to_advanced.htm
Advertisements