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

Gary Gibson
Gary Gibson
5,011 Points

Why use elif and else in this situation when if without else works?

Here is the code as given in the lesson:

item_list = []

def show_help():
    print("""Enter your items here.
Enter SHOW to show your list so far.
Enter DONE or QUIT to stop.
Enter HELP to show this guide.""")

def show_list():
    for item in item_list:
        print(item)

show_help()

while True:
    item = input("Enter an item. > ")

    if item == 'SHOW':
        show_list()
        continue

    elif item == 'HELP':
        show_help()
        continue

    elif item == 'QUIT' or item == 'DONE':
        show_list()
        break

    else:
               item_list.append(item)

But I tried it this way and it worked:

item_list = []

def show_help():
    print("""Enter your items here.
Enter SHOW to show your list so far.
Enter DONE or QUIT to stop.
Enter HELP to show this guide.""")

def show_list():
    for item in item_list:
        print(item)

show_help()

while True:
    item = input("Enter an item. > ")

    if item == 'SHOW':
        show_list()
        continue

    if item == 'HELP':
        show_help()
        continue

    if item == 'QUIT' or item == 'DONE':
        show_list()
        break

    item_list.append(item)

Why is it preferable to use elif and else?

1 Answer

Jacob Bergdahl
Jacob Bergdahl
29,118 Points

elif is faster. If you only write if the compiler (computer) will check all if-clauses, because they could all be true. If you use elif, then the compiler will skip the rest of the elif-clauses and the else-clause as soon as it reaches a condition that equates to true.