Don't understand why (5 | -2) > 0 is False where (5 or -2) > 0 is True [duplicate]2019 Community Moderator ElectionBoolean operators vs Bitwise operatorsHow to test multiple variables against a value?Python join: why is it string.join(list) instead of list.join(string)?Understanding slice notationUnderstanding Python super() with __init__() methodsPeak detection in a 2D arraydifferentiate null=True, blank=True in djangoWhy is reading lines from stdin much slower in C++ than Python?“Large data” work flows using pandasFind span where condition is True using NumPyWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?Why does “not(True) in [False, True]” return False?

Would mining huge amounts of resources on the Moon change its orbit?

What will the Frenchman say?

How can an organ that provides biological immortality be unable to regenerate?

Single word to change groups

How to read string as hex number in bash?

Can other pieces capture a threatening piece and prevent a checkmate?

The English Debate

Do people actually use the word "kaputt" in conversation?

Why is this tree refusing to shed its dead leaves?

Recursively updating the MLE as new observations stream in

Jem'Hadar, something strange about their life expectancy

Animating wave motion in water

Exposing a company lying about themselves in a tightly knit industry: Is my career at risk on the long run?

Why does Surtur say that Thor is Asgard's doom?

pipe commands inside find -exec?

UK Tourist Visa- Enquiry

How do you justify more code being written by following clean code practices?

What is 露わになる affecting in the following sentence, '才能の持ち主' (持ち主 to be specific) or '才能'?

Did Nintendo change its mind about 68000 SNES?

Is xar preinstalled on macOS?

What is the tangent at a sharp point on a curve?

How to balance a monster modification (zombie)?

TDE Master Key Rotation

Are hand made posters acceptable in Academia?



Don't understand why (5 | -2) > 0 is False where (5 or -2) > 0 is True [duplicate]



2019 Community Moderator ElectionBoolean operators vs Bitwise operatorsHow to test multiple variables against a value?Python join: why is it string.join(list) instead of list.join(string)?Understanding slice notationUnderstanding Python super() with __init__() methodsPeak detection in a 2D arraydifferentiate null=True, blank=True in djangoWhy is reading lines from stdin much slower in C++ than Python?“Large data” work flows using pandasFind span where condition is True using NumPyWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?Why does “not(True) in [False, True]” return False?










13
















This question already has an answer here:



  • Boolean operators vs Bitwise operators

    8 answers



This is a pretty trivial question that I haven't been able to find the answer to.



Here is the problem. I have the following array:



vals = [-5, 2]


And I want to check whether val[0] or val[1] is greater than 0. If either is true, then I should output True.



My immediate thought was to use; (vals[1] or vals[0]) > 0) but I'm finding that (5 | -2) > 0 is False where (5 or -2) > 0 is True



Any clarification would be much appreciated.










share|improve this question













marked as duplicate by Christian Dean python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 6





    | is a bitwise operator, not the logical or.

    – Matthias
    11 hours ago






  • 6





    x or y == x for any non-zero x.

    – chepner
    11 hours ago






  • 1





    @chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

    – Benjamin R
    5 hours ago











  • Related: How to test multiple variables against a value?

    – pault
    5 hours ago
















13
















This question already has an answer here:



  • Boolean operators vs Bitwise operators

    8 answers



This is a pretty trivial question that I haven't been able to find the answer to.



Here is the problem. I have the following array:



vals = [-5, 2]


And I want to check whether val[0] or val[1] is greater than 0. If either is true, then I should output True.



My immediate thought was to use; (vals[1] or vals[0]) > 0) but I'm finding that (5 | -2) > 0 is False where (5 or -2) > 0 is True



Any clarification would be much appreciated.










share|improve this question













marked as duplicate by Christian Dean python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 6





    | is a bitwise operator, not the logical or.

    – Matthias
    11 hours ago






  • 6





    x or y == x for any non-zero x.

    – chepner
    11 hours ago






  • 1





    @chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

    – Benjamin R
    5 hours ago











  • Related: How to test multiple variables against a value?

    – pault
    5 hours ago














13












13








13









This question already has an answer here:



  • Boolean operators vs Bitwise operators

    8 answers



This is a pretty trivial question that I haven't been able to find the answer to.



Here is the problem. I have the following array:



vals = [-5, 2]


And I want to check whether val[0] or val[1] is greater than 0. If either is true, then I should output True.



My immediate thought was to use; (vals[1] or vals[0]) > 0) but I'm finding that (5 | -2) > 0 is False where (5 or -2) > 0 is True



Any clarification would be much appreciated.










share|improve this question















This question already has an answer here:



  • Boolean operators vs Bitwise operators

    8 answers



This is a pretty trivial question that I haven't been able to find the answer to.



Here is the problem. I have the following array:



vals = [-5, 2]


And I want to check whether val[0] or val[1] is greater than 0. If either is true, then I should output True.



My immediate thought was to use; (vals[1] or vals[0]) > 0) but I'm finding that (5 | -2) > 0 is False where (5 or -2) > 0 is True



Any clarification would be much appreciated.





This question already has an answer here:



  • Boolean operators vs Bitwise operators

    8 answers







python conditional






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 11 hours ago









madsthaksmadsthaks

7272722




7272722




marked as duplicate by Christian Dean python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Christian Dean python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 hours ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 6





    | is a bitwise operator, not the logical or.

    – Matthias
    11 hours ago






  • 6





    x or y == x for any non-zero x.

    – chepner
    11 hours ago






  • 1





    @chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

    – Benjamin R
    5 hours ago











  • Related: How to test multiple variables against a value?

    – pault
    5 hours ago













  • 6





    | is a bitwise operator, not the logical or.

    – Matthias
    11 hours ago






  • 6





    x or y == x for any non-zero x.

    – chepner
    11 hours ago






  • 1





    @chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

    – Benjamin R
    5 hours ago











  • Related: How to test multiple variables against a value?

    – pault
    5 hours ago








6




6





| is a bitwise operator, not the logical or.

– Matthias
11 hours ago





| is a bitwise operator, not the logical or.

– Matthias
11 hours ago




6




6





x or y == x for any non-zero x.

– chepner
11 hours ago





x or y == x for any non-zero x.

– chepner
11 hours ago




1




1





@chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

– Benjamin R
5 hours ago





@chepner Indeed! Don't assume operator precedence, nor that the interpreter knows what you mean.

– Benjamin R
5 hours ago













Related: How to test multiple variables against a value?

– pault
5 hours ago






Related: How to test multiple variables against a value?

– pault
5 hours ago













6 Answers
6






active

oldest

votes


















37














What is the difference between or and |?



or is a logical or and | is a bitwise or logical inclusive or.



The logical or



The logical or in python returns the first value that is true.



Example:



>>> None or False or 5
5
>>> -5 or 2
-5


The bitwise or logical inclusive or



The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.



Example:



  • 2 is in binary 0010

  • 4 is in binary 0100

A logical or between the two results in 0110 which is 6.



>>> 2 | 4
6


How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.



That number in bitwise ore two any other number still results in a negative number:



>>> -5 | 2
-5


Neither of the two solves your problem



While using



(vals[1] or vals[0]) > 0


seems to work, it fails when you flip the values:



>>> vals = [2, -5]
>>> (vals[1] or vals[0]) > 0
False


You should check both values seperatly



>>> vals = [-5, 2]
>>> vals[0] > 0 or vals[1] > 0
True


For a larger input this may be inconvenient. You should use any with a generator expression:



>>> any(x > 0 for x in vals)
True





share|improve this answer




















  • 1





    These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

    – Ilmari Karonen
    4 hours ago






  • 1





    Yeah, the docs for the built-in types have several hints suggesting that.

    – kalehmann
    4 hours ago











  • Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

    – Ilmari Karonen
    3 hours ago


















12














You want the any function:



>>> any(x > 0 for x in vals)


x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.



What you want to compare each value to zero (as necessary), with



vals[0] > 0 or vals[1] > 0


If you had three values, you'd write



vals[0] > 0 or vals[1] > 0 or vals[2] > 0


The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.






share|improve this answer






























    3














    | is a bitwise OR, and Python uses two's complement representation for integers. Evaluating 5 | -2 gives:



     ... 0000 0000 0000 0101 (+5)
    | ... 1111 1111 1111 1110 (-2)
    ──────────────────────────────
    = ... 1111 1111 1111 1111 (-1)


    And -1 is not greater than zero, so (5 | -2) > 0 is false.



    or is a logical OR. Unlike in other languages where this operator returns a Boolean (True/False) value, Python defines x or y as being equivalent to x if x else y (except that x is evaluated only once). Note that any nonzero numeric value is “truthy” in Python, so if x≠0, then x or y evaluates to x.



    >>> 5 or -2
    5
    >>> -2 or 5
    -2


    That (5 or -2) > 0 evaluates to True was a stroke of luck from having the positive number first. In the other order, you would have gotten False.



    In general (x or y) > 0 is not equivalent to (x > 0) or (y > 0), which is what you meant.






    share|improve this answer























    • I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

      – user1717828
      7 hours ago






    • 2





      @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

      – Dawood ibn Kareem
      7 hours ago











    • Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

      – wizzwizz4
      5 hours ago


















    3














    To answer this question, I have to explain about Two's Complement.



    BINARY REPRESENTATION OF NUMBERS



    So you know how internally, an integer like 5 is represented as a binary string



    00000000000000000000000000000101


    How do you imagine you'd represent a negative number?



    Well, here's what we want to do:



    • Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.


    • Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE, MIN_VALUE - 1 == MAX_VALUE


    So what we do is called "Two's Complement."



    TWO'S COMPLEMENT



    To represent a negative number, take its absolute value, bitflip every bit, and add 1.



    So if the positive number is 5



    00000000000000000000000000000101


    the negative number -5 is



    11111111111111111111111111111011


    Essentially, this means we pick the number 01111111111111111111111111111111 to be the largest positive number, and all numbers after that are negative.



    SO WHAT DOES (5 | -2) MEAN?



    The | is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:



     5 -> 00000000000000000000000000000101
    | -2 -> 11111111111111111111111111111110
    ---- --------------------------------
    11111111111111111111111111111111 -> -1


    So as you can see, 5 | -2 = -1 < 0.



    WHAT ABOUT (5 or -2)?



    The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.



    The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.






    share|improve this answer








    New contributor




    Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




















    • One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

      – Benjamin R
      5 hours ago












    • Brilliant explanation! One thing missing; how do you do the thing OP wanted?

      – wizzwizz4
      5 hours ago












    • You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

      – Q Science
      5 hours ago












    • def atLeastOnePositive(vals): for val in vals: if val > 0: return True

      – Q Science
      5 hours ago











    • return False # outside the for loop, if no element is > 0

      – Q Science
      5 hours ago


















    2














    When you do (5 | -2), you're doing a bitwise-OR. That will preserve the negation bit in the numbers. Therefore, you'll still have a negative number.



    The (5 or -2) is a logical-OR, to the Python interpreter will extend that to the next logical operator (the greater-than).






    share|improve this answer






























      1














      They are two completely different operations so that is expected.



      To illustrate, here's a small shell log:



      In [1]: 5 or -2
      Out[1]: 5

      In [2]: 5 | -2
      Out[2]: -1


      The or operator returns the first non-zero (non-None, non-False, etc.) value.



      The | operator does a bitwise or. To illustrate:



      In [3]: bin(5)
      Out[3]: '0b101'

      In [4]: bin(-2)
      Out[4]: '-0b10'

      In [5]: bin(5 | -2)
      Out[5]: '-0b1'





      share|improve this answer





























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        37














        What is the difference between or and |?



        or is a logical or and | is a bitwise or logical inclusive or.



        The logical or



        The logical or in python returns the first value that is true.



        Example:



        >>> None or False or 5
        5
        >>> -5 or 2
        -5


        The bitwise or logical inclusive or



        The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.



        Example:



        • 2 is in binary 0010

        • 4 is in binary 0100

        A logical or between the two results in 0110 which is 6.



        >>> 2 | 4
        6


        How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.



        That number in bitwise ore two any other number still results in a negative number:



        >>> -5 | 2
        -5


        Neither of the two solves your problem



        While using



        (vals[1] or vals[0]) > 0


        seems to work, it fails when you flip the values:



        >>> vals = [2, -5]
        >>> (vals[1] or vals[0]) > 0
        False


        You should check both values seperatly



        >>> vals = [-5, 2]
        >>> vals[0] > 0 or vals[1] > 0
        True


        For a larger input this may be inconvenient. You should use any with a generator expression:



        >>> any(x > 0 for x in vals)
        True





        share|improve this answer




















        • 1





          These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

          – Ilmari Karonen
          4 hours ago






        • 1





          Yeah, the docs for the built-in types have several hints suggesting that.

          – kalehmann
          4 hours ago











        • Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

          – Ilmari Karonen
          3 hours ago















        37














        What is the difference between or and |?



        or is a logical or and | is a bitwise or logical inclusive or.



        The logical or



        The logical or in python returns the first value that is true.



        Example:



        >>> None or False or 5
        5
        >>> -5 or 2
        -5


        The bitwise or logical inclusive or



        The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.



        Example:



        • 2 is in binary 0010

        • 4 is in binary 0100

        A logical or between the two results in 0110 which is 6.



        >>> 2 | 4
        6


        How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.



        That number in bitwise ore two any other number still results in a negative number:



        >>> -5 | 2
        -5


        Neither of the two solves your problem



        While using



        (vals[1] or vals[0]) > 0


        seems to work, it fails when you flip the values:



        >>> vals = [2, -5]
        >>> (vals[1] or vals[0]) > 0
        False


        You should check both values seperatly



        >>> vals = [-5, 2]
        >>> vals[0] > 0 or vals[1] > 0
        True


        For a larger input this may be inconvenient. You should use any with a generator expression:



        >>> any(x > 0 for x in vals)
        True





        share|improve this answer




















        • 1





          These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

          – Ilmari Karonen
          4 hours ago






        • 1





          Yeah, the docs for the built-in types have several hints suggesting that.

          – kalehmann
          4 hours ago











        • Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

          – Ilmari Karonen
          3 hours ago













        37












        37








        37







        What is the difference between or and |?



        or is a logical or and | is a bitwise or logical inclusive or.



        The logical or



        The logical or in python returns the first value that is true.



        Example:



        >>> None or False or 5
        5
        >>> -5 or 2
        -5


        The bitwise or logical inclusive or



        The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.



        Example:



        • 2 is in binary 0010

        • 4 is in binary 0100

        A logical or between the two results in 0110 which is 6.



        >>> 2 | 4
        6


        How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.



        That number in bitwise ore two any other number still results in a negative number:



        >>> -5 | 2
        -5


        Neither of the two solves your problem



        While using



        (vals[1] or vals[0]) > 0


        seems to work, it fails when you flip the values:



        >>> vals = [2, -5]
        >>> (vals[1] or vals[0]) > 0
        False


        You should check both values seperatly



        >>> vals = [-5, 2]
        >>> vals[0] > 0 or vals[1] > 0
        True


        For a larger input this may be inconvenient. You should use any with a generator expression:



        >>> any(x > 0 for x in vals)
        True





        share|improve this answer















        What is the difference between or and |?



        or is a logical or and | is a bitwise or logical inclusive or.



        The logical or



        The logical or in python returns the first value that is true.



        Example:



        >>> None or False or 5
        5
        >>> -5 or 2
        -5


        The bitwise or logical inclusive or



        The bitwise or logical inclusive or is represented by the | operator in python and creates a number where all bits are set that are set in at least one of the given numbers.



        Example:



        • 2 is in binary 0010

        • 4 is in binary 0100

        A logical or between the two results in 0110 which is 6.



        >>> 2 | 4
        6


        How a negative number is stored is generally implementation specific. However on most systems a negative number is stored by creating the two's complement of the positive number by inverting each bit and adding 1.



        That number in bitwise ore two any other number still results in a negative number:



        >>> -5 | 2
        -5


        Neither of the two solves your problem



        While using



        (vals[1] or vals[0]) > 0


        seems to work, it fails when you flip the values:



        >>> vals = [2, -5]
        >>> (vals[1] or vals[0]) > 0
        False


        You should check both values seperatly



        >>> vals = [-5, 2]
        >>> vals[0] > 0 or vals[1] > 0
        True


        For a larger input this may be inconvenient. You should use any with a generator expression:



        >>> any(x > 0 for x in vals)
        True






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 5 hours ago

























        answered 11 hours ago









        kalehmannkalehmann

        2,703722




        2,703722







        • 1





          These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

          – Ilmari Karonen
          4 hours ago






        • 1





          Yeah, the docs for the built-in types have several hints suggesting that.

          – kalehmann
          4 hours ago











        • Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

          – Ilmari Karonen
          3 hours ago












        • 1





          These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

          – Ilmari Karonen
          4 hours ago






        • 1





          Yeah, the docs for the built-in types have several hints suggesting that.

          – kalehmann
          4 hours ago











        • Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

          – Ilmari Karonen
          3 hours ago







        1




        1





        These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

        – Ilmari Karonen
        4 hours ago





        These are Python ints, not native CPU integers; I'm pretty sure they're explicitly specified to use two's complement. (That said, I'm having a surprisingly hard time locating such a specification. The closest I've found is this wiki page, which is explicit enough but perhaps not fully authoritative, and an oblique remark in the docs saying that "The bitwise inversion of x is defined as -(x+1).")

        – Ilmari Karonen
        4 hours ago




        1




        1





        Yeah, the docs for the built-in types have several hints suggesting that.

        – kalehmann
        4 hours ago





        Yeah, the docs for the built-in types have several hints suggesting that.

        – kalehmann
        4 hours ago













        Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

        – Ilmari Karonen
        3 hours ago





        Good find. In fact, that page explicitly says that "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."

        – Ilmari Karonen
        3 hours ago













        12














        You want the any function:



        >>> any(x > 0 for x in vals)


        x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.



        What you want to compare each value to zero (as necessary), with



        vals[0] > 0 or vals[1] > 0


        If you had three values, you'd write



        vals[0] > 0 or vals[1] > 0 or vals[2] > 0


        The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.






        share|improve this answer



























          12














          You want the any function:



          >>> any(x > 0 for x in vals)


          x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.



          What you want to compare each value to zero (as necessary), with



          vals[0] > 0 or vals[1] > 0


          If you had three values, you'd write



          vals[0] > 0 or vals[1] > 0 or vals[2] > 0


          The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.






          share|improve this answer

























            12












            12








            12







            You want the any function:



            >>> any(x > 0 for x in vals)


            x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.



            What you want to compare each value to zero (as necessary), with



            vals[0] > 0 or vals[1] > 0


            If you had three values, you'd write



            vals[0] > 0 or vals[1] > 0 or vals[2] > 0


            The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.






            share|improve this answer













            You want the any function:



            >>> any(x > 0 for x in vals)


            x | y computes the bitwise OR of the two values, while x or y evaluates to the first "truthy" value. In both cases, the result is then compared to 0: (x or y) > 0 and (x | y) > 0.



            What you want to compare each value to zero (as necessary), with



            vals[0] > 0 or vals[1] > 0


            If you had three values, you'd write



            vals[0] > 0 or vals[1] > 0 or vals[2] > 0


            The any function generalizes this to a list of any size, without the need to decide how many terms to or together based on the size of the list.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 11 hours ago









            chepnerchepner

            257k34247340




            257k34247340





















                3














                | is a bitwise OR, and Python uses two's complement representation for integers. Evaluating 5 | -2 gives:



                 ... 0000 0000 0000 0101 (+5)
                | ... 1111 1111 1111 1110 (-2)
                ──────────────────────────────
                = ... 1111 1111 1111 1111 (-1)


                And -1 is not greater than zero, so (5 | -2) > 0 is false.



                or is a logical OR. Unlike in other languages where this operator returns a Boolean (True/False) value, Python defines x or y as being equivalent to x if x else y (except that x is evaluated only once). Note that any nonzero numeric value is “truthy” in Python, so if x≠0, then x or y evaluates to x.



                >>> 5 or -2
                5
                >>> -2 or 5
                -2


                That (5 or -2) > 0 evaluates to True was a stroke of luck from having the positive number first. In the other order, you would have gotten False.



                In general (x or y) > 0 is not equivalent to (x > 0) or (y > 0), which is what you meant.






                share|improve this answer























                • I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                  – user1717828
                  7 hours ago






                • 2





                  @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                  – Dawood ibn Kareem
                  7 hours ago











                • Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                  – wizzwizz4
                  5 hours ago















                3














                | is a bitwise OR, and Python uses two's complement representation for integers. Evaluating 5 | -2 gives:



                 ... 0000 0000 0000 0101 (+5)
                | ... 1111 1111 1111 1110 (-2)
                ──────────────────────────────
                = ... 1111 1111 1111 1111 (-1)


                And -1 is not greater than zero, so (5 | -2) > 0 is false.



                or is a logical OR. Unlike in other languages where this operator returns a Boolean (True/False) value, Python defines x or y as being equivalent to x if x else y (except that x is evaluated only once). Note that any nonzero numeric value is “truthy” in Python, so if x≠0, then x or y evaluates to x.



                >>> 5 or -2
                5
                >>> -2 or 5
                -2


                That (5 or -2) > 0 evaluates to True was a stroke of luck from having the positive number first. In the other order, you would have gotten False.



                In general (x or y) > 0 is not equivalent to (x > 0) or (y > 0), which is what you meant.






                share|improve this answer























                • I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                  – user1717828
                  7 hours ago






                • 2





                  @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                  – Dawood ibn Kareem
                  7 hours ago











                • Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                  – wizzwizz4
                  5 hours ago













                3












                3








                3







                | is a bitwise OR, and Python uses two's complement representation for integers. Evaluating 5 | -2 gives:



                 ... 0000 0000 0000 0101 (+5)
                | ... 1111 1111 1111 1110 (-2)
                ──────────────────────────────
                = ... 1111 1111 1111 1111 (-1)


                And -1 is not greater than zero, so (5 | -2) > 0 is false.



                or is a logical OR. Unlike in other languages where this operator returns a Boolean (True/False) value, Python defines x or y as being equivalent to x if x else y (except that x is evaluated only once). Note that any nonzero numeric value is “truthy” in Python, so if x≠0, then x or y evaluates to x.



                >>> 5 or -2
                5
                >>> -2 or 5
                -2


                That (5 or -2) > 0 evaluates to True was a stroke of luck from having the positive number first. In the other order, you would have gotten False.



                In general (x or y) > 0 is not equivalent to (x > 0) or (y > 0), which is what you meant.






                share|improve this answer













                | is a bitwise OR, and Python uses two's complement representation for integers. Evaluating 5 | -2 gives:



                 ... 0000 0000 0000 0101 (+5)
                | ... 1111 1111 1111 1110 (-2)
                ──────────────────────────────
                = ... 1111 1111 1111 1111 (-1)


                And -1 is not greater than zero, so (5 | -2) > 0 is false.



                or is a logical OR. Unlike in other languages where this operator returns a Boolean (True/False) value, Python defines x or y as being equivalent to x if x else y (except that x is evaluated only once). Note that any nonzero numeric value is “truthy” in Python, so if x≠0, then x or y evaluates to x.



                >>> 5 or -2
                5
                >>> -2 or 5
                -2


                That (5 or -2) > 0 evaluates to True was a stroke of luck from having the positive number first. In the other order, you would have gotten False.



                In general (x or y) > 0 is not equivalent to (x > 0) or (y > 0), which is what you meant.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 11 hours ago









                dan04dan04

                63.5k15135174




                63.5k15135174












                • I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                  – user1717828
                  7 hours ago






                • 2





                  @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                  – Dawood ibn Kareem
                  7 hours ago











                • Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                  – wizzwizz4
                  5 hours ago

















                • I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                  – user1717828
                  7 hours ago






                • 2





                  @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                  – Dawood ibn Kareem
                  7 hours ago











                • Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                  – wizzwizz4
                  5 hours ago
















                I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                – user1717828
                7 hours ago





                I feel dumb, but why is all 1s equal to -1 and not 2^16 or whatever?

                – user1717828
                7 hours ago




                2




                2





                @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                – Dawood ibn Kareem
                7 hours ago





                @user1717828 because the usual convention is that the most significant bit is taken as negative; so -2^31 for a 4-byte integer. This allows for the storage of a good range of positive and negative numbers. If all the bits were taken as positive, you'd only be able to represent positive numbers, which in many contexts would be less useful.

                – Dawood ibn Kareem
                7 hours ago













                Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                – wizzwizz4
                5 hours ago





                Also, Python takes this to the extreme; -1 is represented by an infinite number of 1s. (It's compressed in memory, in the CPython (reference) implementation.)

                – wizzwizz4
                5 hours ago











                3














                To answer this question, I have to explain about Two's Complement.



                BINARY REPRESENTATION OF NUMBERS



                So you know how internally, an integer like 5 is represented as a binary string



                00000000000000000000000000000101


                How do you imagine you'd represent a negative number?



                Well, here's what we want to do:



                • Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.


                • Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE, MIN_VALUE - 1 == MAX_VALUE


                So what we do is called "Two's Complement."



                TWO'S COMPLEMENT



                To represent a negative number, take its absolute value, bitflip every bit, and add 1.



                So if the positive number is 5



                00000000000000000000000000000101


                the negative number -5 is



                11111111111111111111111111111011


                Essentially, this means we pick the number 01111111111111111111111111111111 to be the largest positive number, and all numbers after that are negative.



                SO WHAT DOES (5 | -2) MEAN?



                The | is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:



                 5 -> 00000000000000000000000000000101
                | -2 -> 11111111111111111111111111111110
                ---- --------------------------------
                11111111111111111111111111111111 -> -1


                So as you can see, 5 | -2 = -1 < 0.



                WHAT ABOUT (5 or -2)?



                The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.



                The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.






                share|improve this answer








                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




















                • One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                  – Benjamin R
                  5 hours ago












                • Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                  – wizzwizz4
                  5 hours ago












                • You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                  – Q Science
                  5 hours ago












                • def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                  – Q Science
                  5 hours ago











                • return False # outside the for loop, if no element is > 0

                  – Q Science
                  5 hours ago















                3














                To answer this question, I have to explain about Two's Complement.



                BINARY REPRESENTATION OF NUMBERS



                So you know how internally, an integer like 5 is represented as a binary string



                00000000000000000000000000000101


                How do you imagine you'd represent a negative number?



                Well, here's what we want to do:



                • Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.


                • Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE, MIN_VALUE - 1 == MAX_VALUE


                So what we do is called "Two's Complement."



                TWO'S COMPLEMENT



                To represent a negative number, take its absolute value, bitflip every bit, and add 1.



                So if the positive number is 5



                00000000000000000000000000000101


                the negative number -5 is



                11111111111111111111111111111011


                Essentially, this means we pick the number 01111111111111111111111111111111 to be the largest positive number, and all numbers after that are negative.



                SO WHAT DOES (5 | -2) MEAN?



                The | is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:



                 5 -> 00000000000000000000000000000101
                | -2 -> 11111111111111111111111111111110
                ---- --------------------------------
                11111111111111111111111111111111 -> -1


                So as you can see, 5 | -2 = -1 < 0.



                WHAT ABOUT (5 or -2)?



                The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.



                The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.






                share|improve this answer








                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




















                • One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                  – Benjamin R
                  5 hours ago












                • Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                  – wizzwizz4
                  5 hours ago












                • You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                  – Q Science
                  5 hours ago












                • def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                  – Q Science
                  5 hours ago











                • return False # outside the for loop, if no element is > 0

                  – Q Science
                  5 hours ago













                3












                3








                3







                To answer this question, I have to explain about Two's Complement.



                BINARY REPRESENTATION OF NUMBERS



                So you know how internally, an integer like 5 is represented as a binary string



                00000000000000000000000000000101


                How do you imagine you'd represent a negative number?



                Well, here's what we want to do:



                • Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.


                • Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE, MIN_VALUE - 1 == MAX_VALUE


                So what we do is called "Two's Complement."



                TWO'S COMPLEMENT



                To represent a negative number, take its absolute value, bitflip every bit, and add 1.



                So if the positive number is 5



                00000000000000000000000000000101


                the negative number -5 is



                11111111111111111111111111111011


                Essentially, this means we pick the number 01111111111111111111111111111111 to be the largest positive number, and all numbers after that are negative.



                SO WHAT DOES (5 | -2) MEAN?



                The | is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:



                 5 -> 00000000000000000000000000000101
                | -2 -> 11111111111111111111111111111110
                ---- --------------------------------
                11111111111111111111111111111111 -> -1


                So as you can see, 5 | -2 = -1 < 0.



                WHAT ABOUT (5 or -2)?



                The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.



                The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.






                share|improve this answer








                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.










                To answer this question, I have to explain about Two's Complement.



                BINARY REPRESENTATION OF NUMBERS



                So you know how internally, an integer like 5 is represented as a binary string



                00000000000000000000000000000101


                How do you imagine you'd represent a negative number?



                Well, here's what we want to do:



                • Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.


                • Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE, MIN_VALUE - 1 == MAX_VALUE


                So what we do is called "Two's Complement."



                TWO'S COMPLEMENT



                To represent a negative number, take its absolute value, bitflip every bit, and add 1.



                So if the positive number is 5



                00000000000000000000000000000101


                the negative number -5 is



                11111111111111111111111111111011


                Essentially, this means we pick the number 01111111111111111111111111111111 to be the largest positive number, and all numbers after that are negative.



                SO WHAT DOES (5 | -2) MEAN?



                The | is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:



                 5 -> 00000000000000000000000000000101
                | -2 -> 11111111111111111111111111111110
                ---- --------------------------------
                11111111111111111111111111111111 -> -1


                So as you can see, 5 | -2 = -1 < 0.



                WHAT ABOUT (5 or -2)?



                The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.



                The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.







                share|improve this answer








                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer






                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered 7 hours ago









                Q ScienceQ Science

                445




                445




                New contributor




                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                Q Science is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.












                • One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                  – Benjamin R
                  5 hours ago












                • Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                  – wizzwizz4
                  5 hours ago












                • You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                  – Q Science
                  5 hours ago












                • def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                  – Q Science
                  5 hours ago











                • return False # outside the for loop, if no element is > 0

                  – Q Science
                  5 hours ago

















                • One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                  – Benjamin R
                  5 hours ago












                • Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                  – wizzwizz4
                  5 hours ago












                • You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                  – Q Science
                  5 hours ago












                • def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                  – Q Science
                  5 hours ago











                • return False # outside the for loop, if no element is > 0

                  – Q Science
                  5 hours ago
















                One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                – Benjamin R
                5 hours ago






                One of those times when going to school for CS is actually useful, isn't it? Nice, complete answer. Welcome to SO!

                – Benjamin R
                5 hours ago














                Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                – wizzwizz4
                5 hours ago






                Brilliant explanation! One thing missing; how do you do the thing OP wanted?

                – wizzwizz4
                5 hours ago














                You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                – Q Science
                5 hours ago






                You could say vals[0] > 0 or vals[1] > 0, which might work best as a helper function:

                – Q Science
                5 hours ago














                def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                – Q Science
                5 hours ago





                def atLeastOnePositive(vals): for val in vals: if val > 0: return True

                – Q Science
                5 hours ago













                return False # outside the for loop, if no element is > 0

                – Q Science
                5 hours ago





                return False # outside the for loop, if no element is > 0

                – Q Science
                5 hours ago











                2














                When you do (5 | -2), you're doing a bitwise-OR. That will preserve the negation bit in the numbers. Therefore, you'll still have a negative number.



                The (5 or -2) is a logical-OR, to the Python interpreter will extend that to the next logical operator (the greater-than).






                share|improve this answer



























                  2














                  When you do (5 | -2), you're doing a bitwise-OR. That will preserve the negation bit in the numbers. Therefore, you'll still have a negative number.



                  The (5 or -2) is a logical-OR, to the Python interpreter will extend that to the next logical operator (the greater-than).






                  share|improve this answer

























                    2












                    2








                    2







                    When you do (5 | -2), you're doing a bitwise-OR. That will preserve the negation bit in the numbers. Therefore, you'll still have a negative number.



                    The (5 or -2) is a logical-OR, to the Python interpreter will extend that to the next logical operator (the greater-than).






                    share|improve this answer













                    When you do (5 | -2), you're doing a bitwise-OR. That will preserve the negation bit in the numbers. Therefore, you'll still have a negative number.



                    The (5 or -2) is a logical-OR, to the Python interpreter will extend that to the next logical operator (the greater-than).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 11 hours ago









                    jhill515jhill515

                    115212




                    115212





















                        1














                        They are two completely different operations so that is expected.



                        To illustrate, here's a small shell log:



                        In [1]: 5 or -2
                        Out[1]: 5

                        In [2]: 5 | -2
                        Out[2]: -1


                        The or operator returns the first non-zero (non-None, non-False, etc.) value.



                        The | operator does a bitwise or. To illustrate:



                        In [3]: bin(5)
                        Out[3]: '0b101'

                        In [4]: bin(-2)
                        Out[4]: '-0b10'

                        In [5]: bin(5 | -2)
                        Out[5]: '-0b1'





                        share|improve this answer



























                          1














                          They are two completely different operations so that is expected.



                          To illustrate, here's a small shell log:



                          In [1]: 5 or -2
                          Out[1]: 5

                          In [2]: 5 | -2
                          Out[2]: -1


                          The or operator returns the first non-zero (non-None, non-False, etc.) value.



                          The | operator does a bitwise or. To illustrate:



                          In [3]: bin(5)
                          Out[3]: '0b101'

                          In [4]: bin(-2)
                          Out[4]: '-0b10'

                          In [5]: bin(5 | -2)
                          Out[5]: '-0b1'





                          share|improve this answer

























                            1












                            1








                            1







                            They are two completely different operations so that is expected.



                            To illustrate, here's a small shell log:



                            In [1]: 5 or -2
                            Out[1]: 5

                            In [2]: 5 | -2
                            Out[2]: -1


                            The or operator returns the first non-zero (non-None, non-False, etc.) value.



                            The | operator does a bitwise or. To illustrate:



                            In [3]: bin(5)
                            Out[3]: '0b101'

                            In [4]: bin(-2)
                            Out[4]: '-0b10'

                            In [5]: bin(5 | -2)
                            Out[5]: '-0b1'





                            share|improve this answer













                            They are two completely different operations so that is expected.



                            To illustrate, here's a small shell log:



                            In [1]: 5 or -2
                            Out[1]: 5

                            In [2]: 5 | -2
                            Out[2]: -1


                            The or operator returns the first non-zero (non-None, non-False, etc.) value.



                            The | operator does a bitwise or. To illustrate:



                            In [3]: bin(5)
                            Out[3]: '0b101'

                            In [4]: bin(-2)
                            Out[4]: '-0b10'

                            In [5]: bin(5 | -2)
                            Out[5]: '-0b1'






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 11 hours ago









                            WolphWolph

                            57.3k7107134




                            57.3k7107134













                                Popular posts from this blog

                                How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                                Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                                Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр