-8

I had a doubt on comparision operator in python. I would like to know if it's right or wrong.

I have certain output that is assigned to a variable. So let's say:

result1, result2, result3

Now I do a comparison like

if result1 == 0 and result2 == 0 and result3 == 0: 
    print "Success "
else:
    print "failure"

My doubt is can this comparison done in this format

if 0 in (result1 , result2 ,result3):
    print "Success"
else :
    print "failure"

Is this right using Python? If not, then what's the reason?

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
Tresa
  • 1
  • 1
  • 4

4 Answers4

5

You can do the comparison but your second comparison does not do the same thing as the first.

This comparison will only be True when each of the variables is 0:

if result1 == 0 and result2 == 0 and result3 == 0:

This comparison will be True when at least one of the variables is 0:

if 0 in (result1, result2, result3):

As you can see, that's not quite the same comparison. To perform the same comparison, you can do:

if (0, 0, 0) == (result1, result2, result3):
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
4
if 0 in (result1, result2, result3):

is equivalent to:

if result1==0 or result2==0 or result3==0:

What you want is this:

if (0,0,0) == (result1, result2, result3):

Which is equivalent to:

if result1==0 and result2==0 and result3==0:

You could actually even do this:

if result1==result2==result3==0:

since you're checking to see if all 3 variables equal the same thing.

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
3

In your second example, it will be evaluated to "True" if any of the values is "0", and is not equivalent to and.

If you have multiple results and want to confirm if they all match a given value, I suggest using the all() function:

results = [0, 1, 0]
if all(result == 0 for result in results):
    print "Success"
else:
    print "Failure"

or use any()

if not any(results):
    print "Success"
...

However, this inverse logic is often difficult for me to comprehend at first and perhaps it's more pythonic to check for existence than non-existence. So if you change your logic to check for existence you can just write:

if all(results):
    print "Success"
else:
   print "Failure" 
monkut
  • 42,176
  • 24
  • 124
  • 155
  • 1
    Your last example has the logic backwards - either `all(results)` should `print 'Failure'`, or the condition should be `if not any(results):`. – lvc Jun 25 '12 at 06:57
  • Thanks, I was implying that the underlying data be changed to check for existence, but it was probably unclear. I've added your suggestion of if not any(). – monkut Jun 25 '12 at 07:23
-1

Perhaps do a variadic function?

def allZero(*args):
    for elem in args:
        if elem != 0:
            return False
    return True

if allZero(result1, result2, result3):
    return "Success"
else: 
    return "Failure"

Then you can test as many resultN at once, as you like.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345