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?

What is it called when someone votes for an option that's not their first choice?

"Marked down as someone wanting to sell shares." What does that mean?

What will the Frenchman say?

Do I need to convey a moral for each of my blog post?

Hot air balloons as primitive bombers

Did Nintendo change its mind about 68000 SNES?

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

Is VPN a layer 3 concept?

Why do I have a large white artefact on the rendered image?

Why doesn't the fusion process of the sun speed up?

Why is this tree refusing to shed its dead leaves?

Emojional cryptic crossword

Nested Dynamic SOQL Query

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

How to read string as hex number in bash?

If I cast the Enlarge/Reduce spell on an arrow, what weapon could it count as?

Was World War I a war of liberals against authoritarians?

The English Debate

Should a narrator ever describe things based on a characters view instead of fact?

Homology of the fiber

What are the rules for concealing thieves' tools (or items in general)?

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

Recursively updating the MLE as new observations stream in

Can "few" be used as a subject? If so, what is the rule?



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();

);
);
);
1 hour 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
    9 hours ago






  • 6





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

    – chepner
    9 hours ago






  • 1





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

    – Benjamin R
    4 hours ago











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

    – pault
    3 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();

);
);
);
1 hour 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
    9 hours ago






  • 6





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

    – chepner
    9 hours ago






  • 1





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

    – Benjamin R
    4 hours ago











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

    – pault
    3 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 9 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();

);
);
);
1 hour 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();

);
);
);
1 hour 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
    9 hours ago






  • 6





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

    – chepner
    9 hours ago






  • 1





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

    – Benjamin R
    4 hours ago











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

    – pault
    3 hours ago













  • 6





    | is a bitwise operator, not the logical or.

    – Matthias
    9 hours ago






  • 6





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

    – chepner
    9 hours ago






  • 1





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

    – Benjamin R
    4 hours ago











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

    – pault
    3 hours ago








6




6





| is a bitwise operator, not the logical or.

– Matthias
9 hours ago





| is a bitwise operator, not the logical or.

– Matthias
9 hours ago




6




6





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

– chepner
9 hours ago





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

– chepner
9 hours ago




1




1





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

– Benjamin R
4 hours ago





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

– Benjamin R
4 hours ago













Related: How to test multiple variables against a value?

– pault
3 hours ago






Related: How to test multiple variables against a value?

– pault
3 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
    3 hours ago






  • 1





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

    – kalehmann
    2 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
    1 hour 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
      6 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
      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
      3 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
      4 hours ago












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

      – wizzwizz4
      3 hours ago












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

      – Q Science
      3 hours ago












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

      – Q Science
      3 hours ago











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

      – Q Science
      3 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
          3 hours ago






        • 1





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

          – kalehmann
          2 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
          1 hour 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
          3 hours ago






        • 1





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

          – kalehmann
          2 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
          1 hour 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 3 hours ago

























        answered 9 hours ago









        kalehmannkalehmann

        2,704722




        2,704722







        • 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
          3 hours ago






        • 1





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

          – kalehmann
          2 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
          1 hour 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
          3 hours ago






        • 1





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

          – kalehmann
          2 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
          1 hour 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
        3 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
        3 hours ago




        1




        1





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

        – kalehmann
        2 hours ago





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

        – kalehmann
        2 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
        1 hour 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
        1 hour 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 9 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
                  6 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
                  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
                  3 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
                  6 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
                  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
                  3 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 9 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
                  6 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
                  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
                  3 hours ago

















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

                  – user1717828
                  6 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
                  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
                  3 hours ago
















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

                – user1717828
                6 hours ago





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

                – user1717828
                6 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
                5 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
                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
                3 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
                3 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
                  4 hours ago












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

                  – wizzwizz4
                  3 hours ago












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

                  – Q Science
                  3 hours ago












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

                  – Q Science
                  3 hours ago











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

                  – Q Science
                  3 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
                  4 hours ago












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

                  – wizzwizz4
                  3 hours ago












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

                  – Q Science
                  3 hours ago












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

                  – Q Science
                  3 hours ago











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

                  – Q Science
                  3 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 5 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
                  4 hours ago












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

                  – wizzwizz4
                  3 hours ago












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

                  – Q Science
                  3 hours ago












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

                  – Q Science
                  3 hours ago











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

                  – Q Science
                  3 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
                  4 hours ago












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

                  – wizzwizz4
                  3 hours ago












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

                  – Q Science
                  3 hours ago












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

                  – Q Science
                  3 hours ago











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

                  – Q Science
                  3 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
                4 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
                4 hours ago














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

                – wizzwizz4
                3 hours ago






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

                – wizzwizz4
                3 hours ago














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

                – Q Science
                3 hours ago






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

                – Q Science
                3 hours ago














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

                – Q Science
                3 hours ago





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

                – Q Science
                3 hours ago













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

                – Q Science
                3 hours ago





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

                – Q Science
                3 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 9 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 9 hours ago









                            WolphWolph

                            57.3k7107134




                            57.3k7107134













                                Popular posts from this blog

                                How does Billy Russo acquire his 'Jigsaw' mask? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why does Bane wear the mask?Why does Kylo Ren wear a mask?Why did Captain America remove his mask while fighting Batroc the Leaper?How did the OA acquire her wisdom?Is Billy Breckenridge gay?How does Adrian Toomes hide his earnings from the IRS?What is the state of affairs on Nootka Sound by the end of season 1?How did Tia Dalma acquire Captain Barbossa's body?How is one “Deemed Worthy”, to acquire the Greatsword “Dawn”?How did Karen acquire the handgun?

                                Личност Атрибути на личността | Литература и източници | НавигацияРаждането на личносттаредактиратередактирате

                                A sequel to Domino's tragic life Why Christmas is for Friends Cold comfort at Charles' padSad farewell for Lady JanePS Most watched News videos