Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask Basics Character Builder Items

Alternative to nested if inside of the for loop

At around 1:00 minute into this video, Kenneth said he couldn't think of another way to loop through the categories without including the colors.

Well, thanks to the Jinja templating documentation I found that you can use the following...

(I'm going to include as an answer so this question doesn't remain open the whole time).

3 Answers

Here's an alternative (and much cleaner) solution:

{% for category, choices in options.items() if category != 'colors' %}
...
{% endfor %}

This is of course because of Python's awesome syntax for control structures/loops!

Man I love Python!

Robin Malhotra
Robin Malhotra
14,883 Points

Could you explain how exactly this works? Shouldn't there be an && or something lying around there somewhere?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Robin Malhotra this doesn't need && or anything because Python allows you to apply a condition to the for loop.

Chris Grazioli
Chris Grazioli
31,225 Points

Dumb question about the block syntax:

{% %} whatever you like {% %}

Must you have something like endfor inside the {%%} or is this just convention?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You have to have the {% endfor %}

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Guess who doesn't write a lot of Jinja2? This guy. Thanks for pointing out a better solution.

Robin Malhotra
Robin Malhotra
14,883 Points

Another really really bad way to do this be to slice out the last row (i.e colors) in options. This of course, assumes you're using numpy.

But Iain Simmons' solution is awesome.