A tutoring website wants to add a
simple online calculator to help students
with basic arithmetic. Build a Flask app
that takes two numbers from the user
and displays their sum, difference,
product, and quotient.
[Link]
from flask import Flask, render_template, request
app = Flask(__name__)
@[Link]('/')
def index():
return render_template('[Link]')
@[Link]('/calculate', methods=['POST'])
def calculate():
# Convert inputs to floats
num1 = float([Link]['num1'])
num2 = float([Link]['num2'])
# Perform operations
results = {
"sum": num1 + num2,
"diff": num1 - num2,
"prod": num1 * num2,
"quot": num1 / num2 if num2 != 0 else "Error (Div by 0)"
}
return render_template('[Link]', results=results)
if __name__ == '__main__':
[Link](debug=True)
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Arithmetic Calculator</title>
</head>
<body>
<h1>Basic Arithmetic Calculator</h1>
<form action="/calculate" method="post">
<label for="num1">First Number:</label>
<input type="number" id="num1" name="num1" step="any"
required><br><br>
<label for="num2">Second Number:</label>
<input type="number" id="num2" name="num2" step="any"
required><br><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>
[Link]
<h2>Results:</h2>
<p>Sum: {{ [Link] }}</p>
<p>Difference: {{ [Link] }}</p>
<p>Product: {{ [Link] }}</p>
<p>Quotient: {{ [Link] }}</p>
<a href="/">Try Again</a>