Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use OR,AND in conditionals?

I have found myself many times,with things that I need to be all or at least one equal to something,and I would write something like that:

if a==1 and b==1:
   do something

or

if a==1 or b==1:
   do something

If the number of things is small its ok,but it is still not elegant.So, is there a better way for a significant number of things, to do the above?Thanks.

like image 720
IordanouGiannis Avatar asked May 29 '12 23:05

IordanouGiannis


People also ask

What are the rules in using conditionals?

A conditional sentence is based on the word 'if'. There are always two parts to a conditional sentence – one part beginning with 'if' to describe a possible situation, and the second part which describes the consequence. For example: If it rains, we'll get wet.


1 Answers

Option 1: any / all

For the general case, have a look at any and all:

if all(x == 1 for x in a, b, c, d):

if any(x == 1 for x in a, b, c, d):

You can also use any iterable:

if any(x == 1 for x in states):

Option 2 - chaining and in

For your first example you can use boolean operator chaining:

if a == b == c == d == 1:

For your second example you can use in:

if 1 in states:

Option 3: any/all without a predicate

If you only care whether the value is truthy you can simplify further:

if any(flags):

if all(flags):
like image 195
Mark Byers Avatar answered Sep 27 '22 19:09

Mark Byers