Server-Side Scripting/Iteration/Python (Flask)

app.py

edit
# Demonstrates conditions, while loops and for loops using
# Celsius and Fahrenheit temperature conversion tables.
#
# References:
#   https://www.mathsisfun.com/temperature-conversion.html
#   https://en.wikibooks.org/wiki/Python_Programming
#   https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask

import flask

app = flask.Flask(__name__)

FORM = """
<h1>Temperature Conversion</h1>
<form method="POST">
<p><label for="start">Start:</label>
<input type="text" id="start" name="start" value="0"></p>
<p><label for="stop">Stop:</label>
<input type="text" id="stop" name="stop" value="100"></p>
<p><label for="increment:">Increment</label>
<input type="text" id="increment" name="increment" value="10"></p>
<p><input type="submit" name="submit" value="Celsius">
<input type="submit" name="submit" value="Fahrenheit"></p>
</form>
"""

@app.route('/', methods=["GET"])
def root_get():
    return FORM

@app.route('/', methods=["POST"])
def root_post():
    start = int(flask.request.form["start"])
    stop = int(flask.request.form["stop"])
    increment = int(flask.request.form["increment"])
    submit = flask.request.form["submit"]

    if submit == "Celsius":
        return process_celsius(start, stop, increment)
    elif submit == "Fahrenheit":
        return process_fahrenheit(start, stop, increment)
    else:
        return "Unexpected submit value: " + submit

def process_celsius(start, stop, increment):
    result = "<h1>Temperature Conversion</h1>"
    result += "<table><tr><th>Celsius</th><th>Fahrenheit</th></tr>"
    celsius = start
    while celsius <= stop:
        fahrenheit = celsius * 9 / 5 + 32
        result += f"<tr><td>{celsius}</td>"
        result += f"<td>{fahrenheit:.1f}</td></tr>"
        celsius += increment
    result += "</table>"
    return result

def process_fahrenheit(start, stop, increment):
    result = "<h1>Temperature Conversion</h1>"
    result += "<table><tr><th>Fahrenheit</th><th>Celsius</th></tr>"
    for fahrenheit in range(start, stop + increment, increment):
        celsius = (fahrenheit - 32) * 5 / 9
        result += f"<tr><td>{fahrenheit}</td>"
        result += f"<td>{celsius:.1f}</td></tr>"
    result += "</table>"
    return result

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

Try It

edit

Copy and paste the code above into the following free online development environment or use your own Python (Flask) compiler / interpreter / IDE.

See Also

edit