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 Python Basics (2015) Shopping List App Second Shopping List App

Brian Pitts
PLUS
Brian Pitts
Courses Plus Student 3,826 Points

when 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

If 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.

Yes, 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
PLUS
Brian Pitts
Courses Plus Student 3,826 Points

Let me be more specific. Please see the following code:

click here for example code

Both produce the same result, but the first example that omits "else" is more terse but less clear to me.