'IF' Syntax For Alternative Conditions

James Stroud jstroud at mbi.ucla.edu
Thu Feb 8 06:10:56 EST 2007


rshepard at nospam.appl-ecosys.com wrote:
>   All my python books and references I find on the web have simplistic
> examples of the IF conditional. A few also provide examples of multiple
> conditions that are ANDed; e.g.,
> 	if cond1:
> 	    if cond2:
> 		do_something.
> 
>   However, I cannot find, nor create by trial-and-error, the syntax for
> alternative conditions that are ORed; e.g.,
> 
> 	if cond1 OR if cond2:
> 	    do_something.
> 
>   I've tried using the C syntax for OR (||) but python complained. I'm sure
> there's a way to do this rather than using if cond1: elif cond2: both with
> the same code to execute.
> 
>   Please pass me a pointer so I can learn how to correctly write this.
> 
> Rich

For lots of conditions:

import operator
reduce(operator.or_, list_of_conditions)

e.g.:

py> import operator
py> list_of_conditions = [
...                        'big' < 'small',
...                        'all' > 'half',
...                        'five' > 'one',
...                        'six' <  'seven'
...                      ]
py> list_of_conditions
[True, False, False, False]
py> reduce(operator.or_, list_of_conditions)
True

James



More information about the Python-list mailing list