Using for loop in Flask | Python

In this tutorial, we’ll be learning the implementation of using for loop in the Flask Python framework.

Basically, Flask is a micro web framework written in Python. It was developed by Armin Ronacher. It provides tools and libraries required for making web applications.

Installing flask on terminal

Installing flask on terminal requires the following steps:

  • pip3 install virtualenv – this is to install a virtual network.
  • mkdir ~/Directory_name – making new directory for virtual environment
  • cd Directory_nameĀ  – navigating to the new directory
  • source bin/activate – activating the default bin folder
  • pip install flask – finally inviting flask

Steps for execution:

Implementation requires two files – A python file and an HTML file.

These two files will be stored in separate folders inside our new directory. Here I’ve used the templates folder for my HTML file. I’ve kept the Python file as it is without enclosing in any folder.

Python code:

In this code, a list is made which is to be run in the for loop of the HTML file. The list here is called ‘Coffee_steps’.

from flask import f, render_template

# giving the app_name

My_app_name = f(__name__) 
# list of steps for hot coffee

Coffee_steps =["turn on the stove", "pour milk", "boil it generously","throw a handful of sugar crystals" "Meanwhile, whisk coffee in a mug", "turn off the stove"
           "let the hot milk into the cup while constantly stirring it", "serve hot", "slurp before it cools down to become Not_so_ColdCoffee", "The output is pretty good, leave comments below! "] 
# the homE_pagE


def homE_pagE():  
    return render_template("Coffee_steps.html", len = len(Coffee_steps), Coffee_steps = Coffee_steps) 
if __name__ == '__main__': = True, debug = True)

All the methods belong to the flask module in Python. the main page for this module in Python elaborately defines each method.

This file is saved in the new directory

HTML code:

The HTML code simply requires a for loop as per the jinja template.

    <h1>Steps to make hot Coffee using Python and for loop in Flask</h1> 
<!-- This is the for loop as per jinja template -->
{%for i in range(0, len)%} 


This Coffee_steps.html file is saved in the templates folder.

Executing the Python file on terminal:

The execution requires running the Python file on the terminal or command prompt.

Once the file is executed, an IP address is produced as the output. Carefully, this address is to be copied onto the address bar of the search engine. The output at this step looks like:

python flask debug


Visiting the given address on the search engine, the following output is obtained:

for loop

This is one implementation of For loop in Flask of Python. For further details regarding Flask syntaxes, concepts and methods, refer: Flask-WTF explained; how to use it? For Python, kindly visit the Python reference link.

Leave a Reply