How to Build a Simple Website with Python Backend: Adding Two Numbers with Flask
In this tutorial, you'll learn how to create a simple web application that adds two numbers using Python as the backend and HTML as the frontend. We will use the popular Python web framework Flask to handle the logic. Let's get started!
Step 1: Install Flask
Flask is a lightweight Python framework that helps you build web applications quickly. Install it using the command below:
pip install flask
Step 2: Create the Backend Logic (Python)
We'll start by creating a Python file app.py
that handles the backend logic of our application.
from flask import Flask, render_template, request app = Flask(__name__) # Route to render the HTML page @app.route('/') def index(): return render_template('index.html') # Route to handle the form submission @app.route('/add', methods=['POST']) def add(): num1 = request.form['num1'] num2 = request.form['num2'] result = float(num1) + float(num2) return render_template('index.html', result=result) if __name__ == '__main__': app.run(debug=True)
Step 3: Design the Frontend (HTML)
Create an index.html
file inside a templates
folder. This file will contain the simple form where users can input two numbers and get the sum.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Two Numbers</title> </head> <body> <h1>Add Two Numbers</h1> <form action="/add" method="POST"> <label for="num1">Number 1:</label> <input type="number" id="num1" name="num1" required> <br><br> <label for="num2">Number 2:</label> <input type="number" id="num2" name="num2" required> <br><br> <button type="submit">Add</button> </form> {% if result %} <h2>Result: {{ result }}</h2> {% endif %} </body> </html>
Step 4: Run Your Web App
Now, navigate to your project directory and run your Python script by typing the command:
python app.py
Conclusion
This simple web application shows how easily you can connect Python's backend functionality with an HTML frontend using Flask. It's a great starting project for web development with Python. Give it a try!