2
a = 10
b = 20
c = 30
if(a > b,c):
    print('In if')
else:
    print('In else')

Someone posted the above piece of code, and asked why the above always results in 'In if', being printed regardless of the values of b and c.

Although this seems like poor programming style, I am curious what the , operator is doing.

I have not been able to find an answer in the documentation so far. Can anyone provide an explanation ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

3 Answers3

6

a > b, c is the tuple ((a > b), c).

So if a=10, b=20, c=30, then we're asking if the tuple (False, 30) is truish. All non-empty tuples are truish, so this would always trigger the same path through the conditional.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
2

Example:

>>> 5>4,5
(True, 5)

It outputs a tuple where the elements are the result of 5>4 and 5

as 5>4 equals True

The output will be (True, 5)

a121
  • 798
  • 4
  • 9
  • 20
2

let me start by explaining the what the tuple is resulting:

in your case , since a>b is false, the first part of the tuple is False .

so the (a>b,c) , would look something like (False, 30).

Now you are asking if a tuple has some content in it. Yes , it is of course having the content and that is (False, 30).

That is why your if check is always passing irrespective of values of a,b,c.

If an empty tuple is passed in to the if clause , then you will see the if clause failing, as shown below.

>>> if():
    print('In if')
else:
    print('In else')

    
In else

Regards

Dharman
  • 30,962
  • 25
  • 85
  • 135
McLovin
  • 555
  • 8
  • 20