python - "if", and "elif" chain versus a plain "if" chain -


i wondering, why using elif necessary when this?

if true:     ... if false:     ... ... 

you'd use elif when want ensure one branch picked:

foo = 'bar' spam = 'eggs'  if foo == 'bar':     # elif spam == 'eggs':     # won't this. 

compare with:

foo = 'bar' spam = 'eggs'  if foo == 'bar':     # if spam == 'eggs':     # *and* this. 

with if statements, options not exclusive.

this applies when if branch changes program state such elif test might true too:

foo = 'bar'  if foo == 'bar':     #     foo = 'spam' elif foo == 'spam':     # skipped, if foo == 'spam' true     foo = 'ham' 

here foo set 'spam'.

foo = 'bar'  if foo == 'bar':     #     foo = 'spam' if foo == 'spam':     # executed when foo == 'bar' well,      # previous if statement changed 'spam'.     foo = 'ham' 

now foo set 'spam', 'ham'.

technically speaking, elif part of (compound) if statement; python picks first test in series of if / elif branches tests true, or else branch (if present) if none true. using separate if statement starts new selection, independent of previous if compound statement.


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -