1

I have a piece of code:

x = 8

if x==3 or 4:
    print("yes")
    
else:
    print("no")

It gives "yes".

I know the correct syntax should be if x==3 or x==4. However, I can't seem to explain the result yielded from the wrong syntax and have tried checking it out on PythonTutor. Why does it result in "yes"?

toothpick
  • 125
  • 1
  • 7
  • check these outputs: `print(8==3 or 4)`, `print(bool(4))` – timgeb Oct 26 '21 at 09:12
  • It is called an operator chain. They are a bit tricky... – U. W. Oct 26 '21 at 09:15
  • 1
    @U.W. THis is **not** operator chaining. Chaining occurs with multiple *comparison* operators: `a < b <= c` <-> `a < b and b <= c`. Here, you just have common operator *precedence* being applied: `x == 3 or 4` <-> `(x == 3) or 4`. Note the diffrence from `(x == 3) and (3 or 4)` which would be the case for chaining. – user2390182 Oct 26 '21 at 09:38
  • @Noob The answer to your question is covered in the [linked duplicate](https://stackoverflow.com/q/20002503/3890632). The comment conversation going on here is not important. – khelwood Oct 26 '21 at 10:07

0 Answers0