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 trialBrian Pitts
Courses Plus Student 3,826 Pointswhen should the keyword "else" be included?
when does one include an "else" statement? For example,
if new_item == "DONE": break shopping_list.append(new_item)
VERSUS
if new_item=="DONE": break else: shopping_list.append(new_item)
I realize there is a "best practice" for writing python code which may suggest an answer. Either way works, but the second seems more explicit, albeit verbose. Any thoughts?
3 Answers
jcorum
71,830 PointsIf I understand you, there's a big difference. In pseudo-code:
if x < 2 then
do something
else if x < 3
do something else
else
do a third thing
That's quite different than:
if x < 2 then
do something
do something else
do a third thing
In the latter you will do something else and a third thing regardless of x's value. In the former, that's not the case.
Sorry if I misunderstood.
jcorum
71,830 PointsYes, I see. I missed your point. In such a case, agreed, there's no need for the else. Some might think it "safer", but I don't see it.
Brian Pitts
Courses Plus Student 3,826 PointsLet me be more specific. Please see the following code:
Both produce the same result, but the first example that omits "else" is more terse but less clear to me.