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 Python Basics Types and Branching Comparisons

Quick question about the order of if, elif, else statements.

Is there a certain order when writing conditional code in Python? Does it always start with an if statement followed by an elif and then finished with an else?

What if you have 2 parts would it just be an if then an else?

I'm sorry if this sounds all over the place. I just wanted some clarification.

1 Answer

Some times you only have an if and other times you might have one, more than one or none elif and also one, more than one or none else. Reading this way might be a bit confusing, see if the example below clears some doubts. It reads much like English, if you practice with your own examples you will have a better grasp.

A quick note: an elif or an else will only exist if there is an if first.

color = "blue"

if color == "blue":
    print("1. This will run because the condition is true")
elif color == "blue":
    print("2. This will not run, because the condition above already evaluated to true")

if color == "blue":
    print("3. This will run because the condition is true")
if color == "blue":
    print("4. This will run because the condition is true and it's not linked to the if above")

if color == "blue":
    print("5. This will run because the condition is true")
elif color == "blue":
    print("6. Even though this is true, it will not run because the condition above already evaluated to true")

if color == "blue":
    print("7. This will run because the condition is true")
else:
    print("8. This would only run if the condition above is false")

if color == "blue":
    print("9. This will run because the condition is true")
elif color == "orange":
    print("10. This will not run because the condition is false")
else:
    print("11. This would only run if BOTH the 2 conditions above are false")

I'm saving this for future reference! Thank you so much.