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 trialIain Simmons
Treehouse Moderator 32,305 PointsAlternative 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
Iain Simmons
Treehouse Moderator 32,305 PointsHere'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!
Kenneth Love
Treehouse Guest TeacherGuess who doesn't write a lot of Jinja2? This guy. Thanks for pointing out a better solution.
Robin Malhotra
14,883 PointsAnother 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.
Robin Malhotra
14,883 PointsRobin Malhotra
14,883 PointsCould you explain how exactly this works? Shouldn't there be an && or something lying around there somewhere?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherRobin Malhotra this doesn't need
&&
or anything because Python allows you to apply a condition to thefor
loop.Chris Grazioli
31,225 PointsChris Grazioli
31,225 PointsDumb question about the block syntax:
{% %} whatever you like {% %}
Must you have something like endfor inside the {%%} or is this just convention?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherYou have to have the
{% endfor %}