0

I start learning python. Here is my logic

A = 123
B = 124

if 124 != A or B:
   #do something
   print("value doesn't match")

so above statement shouldn't return print because value 124 == B but why I am getting the print statement? I am not understanding this. I know it's vey silly question but as a beginner I am not understanding this concept. please help me to understand why my or logic return print where I already have matching value.

if I try:

if B != 124:
   #do something
   print("value doesn't match")

then it's working but why not working A or B together ?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
jabodom934
  • 43
  • 1
  • 7
  • 1
    The python keyword ```or ```takes precedence after ```!=```. The statement evaluates to ```(124 != A) or (B)``` rather than ```(124 != A) or (124 != B)``` . In python all numbers except 0 is True, so both ```124 != A``` and ```B``` return True. – MT756 Oct 11 '22 at 21:17
  • @MT756 the issue isn't really *precedence* in this case, the issue is that the `!=` doesn't automatically distribute over the `or` like it does in natural language. – juanpa.arrivillaga Oct 11 '22 at 21:25
  • @juanpa.arrivillaga also tried `(124 != A) or (124 != B) ` but it's returning print statement and don't know why – jabodom934 Oct 11 '22 at 21:33
  • I think you want `and` – juanpa.arrivillaga Oct 11 '22 at 21:44

1 Answers1

0

if 124 != A or B: this will check like this.

It's evaluated separately between `or.

124 != A will give you True and B itself also gives you True.

In [1]: if 124 != A:
     ...:     print("value doesn't match")
     ...: 
# value doesn't match

In [2]: if B:
     ...:     print("value doesn't match")
     ...: 
# value doesn't match

If something not understanding in python take step by step and execute it in the python interpreter.

For the together check you need to write like this,

if 123 != A or 124 != B:
    print("value doesn't match")
Rahul K P
  • 15,740
  • 4
  • 35
  • 52