-1

I'm having trouble understanding something simple:

a = 1
b = 3

if a or b == 0:
    print(a,b)
else:
    print("NO")

I'm just not understanding "or" and "==" be True when it seems not. print(a,b) runs when values are 1,3 .

sudo
  • 19
  • 1

1 Answers1

0

To begin with, the correct way of checking will be if a == 0 or b == 0

In [1]: a = 1 
   ...: b = 3 
   ...:                                                                                                                                                                           

In [2]: if a==0  or b == 0: 
   ...:     print(a,b) 
   ...: else: 
   ...:     print("NO") 
   ...:                                                                                                                                                                           
NO
In [12]: a = 0                                                                                                                                                                    

In [13]: b = 0                                                                                                                                                                    

In [14]: if a==0  or b == 0: 
    ...:     print(a,b) 
    ...: else: 
    ...:     print("NO") 
    ...:                                                                                                                                                                          
0 0

When you do if a or b==0 it evaluates it as if 1, which is True since 1 is interpreted as being True in Python, so it ends up being if a, hence you see (1,3 being printed in the original question

In [9]: a = 1                                                                                                                                                                     

In [10]: b = 3                                                                                                                                                                    

In [11]: if a or b == 0: 
    ...:     print(a,b) 
    ...: else: 
    ...:     print("NO") 
    ...:                                                                                                                                                                          
1 3
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • Great, glad to help @sudo :) Please consider marking the answer as accepted by clicking the tick next to the answer if it helped you :) Also consider reading stackoverflow.com/help/someone-answers – Devesh Kumar Singh May 14 '19 at 10:25