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