Web Calculator (Flask) Project (code) in Python

← Back to Projects

Web Calculator with Flask in Python

About the project: A web calculator built with Flask is a great project for learning how web applications handle user input and perform server-side logic.

This is a complete and self-contained project. This single Python file contains everything you need: the Flask application logic and the HTML for the user interface.


How to Run the Project

  • Install Flask: If you haven't already, open your terminal and install Flask using pip:
    
      pip install Flask
      
  • Save the Code: Save the code above into a file named app.py.
  • Run the App: Navigate to the directory where you saved the file and run it from your terminal:
    
          python app.py
          
  • Access the Calculator: Open your web browser and go to http://127.0.0.1:5000 to see the calculator in action.(in step 4 below)

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE) and run in the browser as instructed above.



# app.py

# Import necessary Flask components
from flask import Flask, render_template_string, request

# Create a new Flask application instance
app = Flask(__name__)

# The HTML content for the calculator page is stored as a multi-line string.
# This makes the entire project a single, self-contained file.
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f4f4f9;
            margin: 0;
        }
        .container {
            background-color: #fff;
            padding: 30px 40px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 16px;
        }
        .form-group button {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 8px;
            background-color: #007bff;
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .form-group button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 20px;
            font-size: 24px;
            font-weight: bold;
            color: #28a745;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Web Calculator</h1>
        
        <!-- The form submits data to the same page using the POST method -->
        <form action="/" method="POST">
            <div class="form-group">
                <input type="number" step="any" name="num1" placeholder="Enter first number" required>
            </div>
            <div class="form-group">
                <select name="operation">
                    <option value="add">+</option>
                    <option value="subtract">-</option>
                    <option value="multiply">*</option>
                    <option value="divide">/</option>
                </select>
            </div>
            <div class="form-group">
                <input type="number" step="any" name="num2" placeholder="Enter second number" required>
            </div>
            <div class="form-group">
                <button type="submit">Calculate</button>
            </div>
        </form>

        <!-- A section to display the result, only shown if a result exists -->
        {% raw %}
        {% if result is defined %}
            <div class="result">
                Result: {{ result }}
            </div>
        {% endif %}
        {% endraw %}
    </div>
</body>
</html>
"""

@app.route('/', methods=['GET', 'POST'])
def calculator():
"""
    Handles both GET and POST requests for the calculator.
    GET: Displays the empty calculator form.
    POST: Processes the calculation and displays the result.
    """
    result = None

    if request.method == 'POST':
        try:
            num1 = float(request.form['num1'])
            num2 = float(request.form['num2'])
            operation = request.form['operation']
            
			 # Perform the calculation based on the selected operation
            if operation == 'add':
                result = num1 + num2
            elif operation == 'subtract':
                result = num1 - num2
            elif operation == 'multiply':
                result = num1 * num2
            elif operation == 'divide':
                if num2 == 0:
                    result = "Error: Division by zero"
                else:
                    result = num1 / num2
                    
			# Format the result to two decimal places if it's not an error message
            if isinstance(result, (int, float)):
                result = f"{result:.2f}"

        except ValueError:
            result = "Error: Invalid number input"

	# Render the HTML template, passing the result to the template context
    return render_template_string(HTML_TEMPLATE, result=result)

if __name__ == '__main__':
# Run the Flask application in debug mode for development
    app.run(debug=True)



← Back to Projects