-3

I come from C background and found this quite strange.

a = 0

b = 0

if (a == b) != 0:
    print('non zero and equal')
else:
    print('something wrong')

This prints "non zero and equal".

In C, a == b evaluates to true, i.e. non-zero. Now, you compare non-zero with zero and this comes to false, i.e. 0.

How does this work in Python?

I tried doing something like this:

if a==b !=0:

It worked but I got to know there is some lazy evaluation there and I need to understand it.

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Prawn Hongs
  • 441
  • 1
  • 5
  • 17
  • 1
    You might like to read [this](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-in-python-how-is-it-different-from-true-and-false) – Harshit Joshi Mar 22 '19 at 04:15
  • 1
    (a == b) gets evaluated first due to parentheses, so effectively you are evaluating True != 0 which is True as True equates to 1 – Vaishali Mar 22 '19 at 04:23
  • 1
    In C, `int a = 0; int b = 0; return (a == b) != 0;`, you get `1`, because you used `!=` for the final 0 comparison. The same thing happens here. – Daniel H Mar 22 '19 at 04:26
  • As others have said, you're mistaken about how C works. It behaves the same as Python here (aside from the first comparison producing `1`, not a special `True` value, but Python's `True` has a numeric value of `1` so it's all basically the same). – ShadowRanger Mar 22 '19 at 04:29
  • The result of comparison of values of a==b is True, which you then, compare with numerical value 0, which is evaluates to False. – hlkstuv_23900 Mar 22 '19 at 04:31

3 Answers3

0

a==b comes to True.

Also, True != 0 which evaluates to True.

Nitin Pandey
  • 649
  • 1
  • 9
  • 27
0

It same as C, when a == b it comes out to be true which is 1

(a == b) != 0

gives

1!= 0

and hence the print statement

Banks
  • 179
  • 13
0

In Python3 True evaluates to 1 and False as 0. Find below for more understanding. Also read this operator comparisons to clear your understanding.

Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True != 0
True
>>> False != 1
True
>>> False == 0
True
>>> True == 1
True
>>> True == 4
False
Pravin
  • 677
  • 2
  • 7
  • 22