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

How to access named pipes using JavaScript in Firefox add-on? -

multithreading - OPAL (Open Phone Abstraction Library) Transport not terminated when reattaching thread? -

node.js - req param returns an empty array -