create a flask app that multiplies two numbers that the user inputs in python

To create a Flask app that multiplies two numbers that the user inputs, follow these steps:

  1. Install Flask using pip: pip install flask

  2. Import Flask and request modules in your Python code:

main.py
from flask import Flask, request
33 chars
2 lines
  1. Create an instance of the Flask class:
main.py
app = Flask(__name__)
22 chars
2 lines
  1. Create a route for the user to input the two numbers:
main.py
@app.route('/multiply')
def multiply():
    html = '''
        <form method="POST" action="/result">
            <label for="num1">Number 1:</label>
            <input type="text" name="num1"><br><br>
            <label for="num2">Number 2:</label>
            <input type="text" name="num2"><br><br>
            <input type="submit" value="Multiply">
        </form>
    '''
    return html
392 chars
13 lines
  1. Create a route for the calculation to take place and display the result:
main.py
@app.route('/result', methods=['POST'])
def result():
    num1 = float(request.form['num1'])
    num2 = float(request.form['num2'])
    result = num1 * num2
    return f'The result of multiplication is {result}'
212 chars
7 lines
  1. Run the Flask app:
main.py
if __name__ == '__main__':
    app.run()
41 chars
3 lines
  1. Open the web browser and go to http://localhost:5000/multiply

  2. Enter the two numbers into the form and click on the "Multiply" button.

  3. The result should be displayed on the page.

Here is the complete code:

main.py
from flask import Flask, request

app = Flask(__name__)

@app.route('/multiply')
def multiply():
    html = '''
        <form method="POST" action="/result">
            <label for="num1">Number 1:</label>
            <input type="text" name="num1"><br><br>
            <label for="num2">Number 2:</label>
            <input type="text" name="num2"><br><br>
            <input type="submit" value="Multiply">
        </form>
    '''
    return html

@app.route('/result', methods=['POST'])
def result():
    num1 = float(request.form['num1'])
    num2 = float(request.form['num2'])
    result = num1 * num2
    return f'The result of multiplication is {result}'

if __name__ == '__main__':
    app.run()
704 chars
27 lines

I hope this helps you!

gistlibby LogSnag