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

tyler borg
tyler borg
9,429 Points

'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

tyler borg
tyler borg
9,429 Points

ok, that helps. thanks.

tyler borg
tyler borg
9,429 Points

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.

tyler borg
tyler borg
9,429 Points

Thank you again.