Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.