0
0
Flaskframework~30 mins

Control structures (if, for) in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Flask Template Control Structures
📖 Scenario: You are building a simple Flask web page that shows a list of fruits and highlights which ones are favorites.
🎯 Goal: Create a Flask template that uses for loops and if statements to display fruits and mark favorites.
📋 What You'll Learn
Create a Python list called fruits with the exact values: 'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'
Create a Python list called favorite_fruits with the exact values: 'Banana', 'Date'
Use a Flask template with a for loop to go through fruits
Use an if statement inside the template to check if the fruit is in favorite_fruits and add '(Favorite)' next to it
💡 Why This Matters
🌍 Real World
Web developers often need to display lists of items with special highlights or conditions, like marking favorites or featured products.
💼 Career
Understanding how to use control structures in Flask templates is essential for backend web developers to create dynamic and user-friendly web pages.
Progress0 / 4 steps
1
Create the fruits list
Create a Python list called fruits with these exact values: 'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'.
Flask
Need a hint?

Use square brackets [] to create a list and separate items with commas.

2
Create the favorite_fruits list
Create a Python list called favorite_fruits with these exact values: 'Banana', 'Date'.
Flask
Need a hint?

Use a list to store favorite fruits, just like the fruits list.

3
Add a for loop in the Flask template
In the Flask template, use a for loop with the variable fruit to iterate over fruits. Inside the loop, display each fruit inside a <li> tag.
Flask
Need a hint?

Use {% for fruit in fruits %} to start the loop and {% endfor %} to end it.

4
Add an if statement to mark favorites
Inside the for loop in the Flask template, add an if statement to check if fruit is in favorite_fruits. If yes, add the text (Favorite) after the fruit name inside the <li> tag.
Flask
Need a hint?

Use {% if fruit in favorite_fruits %} to check and {% endif %} to close the condition.