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

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.