0

I am running Python 3.6.4 with Anaconda and Spyder.

Does anyone know why the following is happening?

When I execute the following code python prints "yes" which it is obviously wrong.

import numpy as np
a = 0
c = np.ones(150)
b = np.ones(10)
if a < len(c) & len(b) < 3:
    print('yes')

While when I made a slight modification the condition is not satisfied and python does not print anything

a = 0
c = np.ones(152)
b = np.ones(10)
if a < len(c) & len(b) < 3:
    print('yes')

Furthermore if I change "&" with "and" everything is working as expected.

gnikol
  • 227
  • 2
  • 9
  • 2
    `&` is *bitwise* and, `and` is *logical* and – Mulan May 17 '18 at 21:54
  • 3
    Does that not suggest you should focus your attention on researching the difference between `&` and `and`? – roganjosh May 17 '18 at 21:54
  • Yes you are correct. But I cannot understand why the first block of code prints "yes" while the second block of code does not print anything – gnikol May 17 '18 at 21:57
  • See explanation of bitwise vs Boolean [here](https://stackoverflow.com/questions/3845018/boolean-operators-vs-bitwise-operators) – mbrig May 17 '18 at 21:57
  • The main difference that you see is summarized [here](https://stackoverflow.com/a/25949622/2285236). `&` has a higher precedence. – ayhan May 17 '18 at 22:00
  • @user633183, But is this really the problem? Nothing wrong with using bitwise operators here. Provided they are using correctly. – jpp May 17 '18 at 22:01
  • Thank you very much. I understand now. I should use "and" or use parenthesis. – gnikol May 17 '18 at 22:04
  • @PaulRooney I think [this answer](https://stackoverflow.com/a/25949622/2285236) covers that? – ayhan May 17 '18 at 22:05
  • `&` is useful when chaining boolean arrays, but you can't use those in an `if` statement. – hpaulj May 18 '18 at 01:11

2 Answers2

2

This is due to operator chaining, & takes precedence. Try this instead, notice the brackets:

if (a < len(c)) & (len(b) < 3):
    print('yes')

& is a bitwise operator and as such may be used to combine two Boolean conditions. In Python, bool is a subclass of int.

Bitwise, len(c) & len(b) evaluates to 2, so you are actually evaluating:

if 0 < 2 < 3:  # i.e. 0 < 2 and separately 2 < 3
jpp
  • 159,742
  • 34
  • 281
  • 339
0

& is a bitwise and. and is logical and. (Use this! It's cleaner and more pythonic).

You can also include more parentheses (a < len(c)) & (len(b) < 3): and that will work, despite being ugly.

JarbingleMan
  • 350
  • 1
  • 12