0

I have a quick question regarding if logic in python. I have the following code:


    def punch(self):
        """Punch method that returns different remarks based on glove weight"""

        if self.weight < 5:
            return "That tickles."
        elif self.weight >= 5 & self.weight < 15:
            return "Hey that hurt!"
        else:
            return "OUCH!"

When I run the following code it always returns “Hey that hurt!”, no matter what weight I assign to self.weight. I am extremely confused as to why that is.

  • 1
    Instead of using `&`, what happens if you use `and`? Also, instead of using `|`, what happens if you use `or`? [Here](https://docs.python.org/3/reference/expressions.html#boolean-operations) is a little more information from the documentation, if it helps! I think `&` [means something different](https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations) than what you might have been expecting, for Python. – summea Feb 13 '21 at 01:51
  • Your question talks about assert statements (which are in fact an actual thing in Python), whereas you have shown if statements. Please stick to standard terminology, this is confusing. – costaparas Feb 13 '21 at 01:53
  • There's no assert here. – user2357112 Feb 13 '21 at 01:56
  • Where exactly did you get the idea to use `&`, was it in some tutorial? You almost certainly intended to use the boolean `and` operator instead. (`&` is the bitwise AND). – costaparas Feb 13 '21 at 02:00
  • I honestly didn't know the difference between the two which has now been clarified. My question is why does adding partheses change the behavior? –  Feb 13 '21 at 02:11

3 Answers3

1

&, |, etc. are bitwise operators, used for things like bit-flipping, etc.

and, or, not, etc. are logical operators, and are what you likely mean to use in situations like these.

Also, as a side note, assert, as you've called it in the title, is something else entirely from logic statements like the ones you've presented.

Chance
  • 440
  • 2
  • 6
1

There is difference between the two operators in Python: & (bitwise AND) and and (boolean AND). & has a higher precedence than and which is why your code behaves differently. Learn more about operator precedence here.

AnkurSaxena
  • 825
  • 7
  • 11
0

In Python, I think you would want to use the terms and or or instead of & and | for what it looks you are wanting to do.

In this particular language, & and | appear to be bitwise operations instead of boolean operations, like I was getting at in my earlier comments.

summea
  • 7,390
  • 4
  • 32
  • 48