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

'if' vs 'elif': can you use either one?

does it really matter if you use "if" or "elif"? Can't you just use multiple "if"s??

3 Answers

elif only executes if the if statement is false. Multiple if statements execute independently. Consider the following example:

a = 5

if a == 5:
    print('yes')
    a = 6
elif a == 6:
    print('no')

this prints yes

a = 5    

if a == 5:
    print('yes')
    a = 6
if a == 6:
    print('no')    

this prints yes no

ok, that helps. thanks.

so if multiple "if" statements can execute independently if they are both true, does that mean that multiple "elif" statements can do the same if they are referencing the same false "if" statement?

No. Just the first elif to evaluate to true. Therefore order is important.

Thank you again.