1

Can Someone Explain the Difference between logical and Boolean & in this code

def isprime(num):
    return [i for i in range(2,num) if num%i==0]==[]

num_which_are_prime=[i for i in range(1,100) if isprime(i) and i!=1]
print(num_which_are_prime)

num_which_are_prime=[i for i in range(1,100) if isprime(i) & i!=1]
print(num_which_are_prime)

Shows this:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

[2, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]

Community
  • 1
  • 1
  • 2
    Please see [Formatting Help](https://stackoverflow.com/help/formatting) to get your code formatted correctly. Images of code aren't great either. – skrrgwasme Jun 07 '18 at 05:12
  • Please add your code (not image of code). It's time consuming writing your code again and explain the answer. It's easier to copy your code and edit it. – Taohidul Islam Jun 07 '18 at 05:15
  • Please write a brief description of your problem. The problem statement that you have posted is not sufficient to understand the problem. – Ganesh Tata Jun 07 '18 at 05:17
  • 1
    Possible duplicate of [Boolean operators vs Bitwise operators](https://stackoverflow.com/questions/3845018/boolean-operators-vs-bitwise-operators) – skrrgwasme Jun 07 '18 at 05:21
  • `&` is bitwise operator, it does NOT produce boolean True/False value. – VPfB Jun 07 '18 at 05:21

1 Answers1

1

Aside from the improper use of & as stated in the comment.

It's because of the operator precedence.

  • and has lower priority than !=
  • != has lower priority than &

So the first expression is evaluated as isprime(i) and (i != 1), the second expression is evaluated as ((isprime(i) & i) != 1).

EDIT

To explain output for the & version. As stated in the comment, & is a bitwise AND operator. Boolean expressions True and False can be represented as a single bit 1 and 0, respectively. As a result, the expression isprime(i) & i tests only the very first bit (the right-most bit)

  • For every non-prime number you get 0 & i which always evaluates to 0 and 0 != 1 is always True.

  • Every prime number, except for 2, is an odd number (that is the first bit is 1). As such, 1 & x1, where x is arbitrary binary string, will evaluate to 1 and 1 != 1 will always be False.

  • And lastly, 2 is a prime number but it's even (first bit is 0). So, 1 & 10 will be 0, and 0 != 1 evaluates to True.

Your output, therefore, contains only non-prime numbers and a number 2.

Aechlys
  • 1,286
  • 7
  • 16