Home > Mobile >  Difference between `==` and `and`
Difference between `==` and `and`

Time:03-08

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 == b > 0) or (a > 0 == b < 0))

so basically I tried some basic problems. I just started out and went to https://codingbat.com/prob/p162058 to try it and don't understand why if I were to replace the '==' with 'and' it would work? Thanks.

Oh, I got it now, thanks guys. :D (this python community is fire!!!)

CodePudding user response:

This "==" means equals to, belonging to Python Comparison Operators, used to compare two values.

and language keyword "and" it is for Python Logical Operators used to combine conditional statements.

You should check out this, it may solve others doubts you have.

W3Schools

CodePudding user response:

and is a logical operator and returns true only when both the expressions we are using it on are true.

== is used for comparisions and returns true when both the expressions are equal; they need not be true.

To give you an example False == False will return True but False and False will return False

CodePudding user response:

All your relational operator usages (i.e. a < 0, b < 0, etc.) result to a boolean value and thus these are known as boolean expressions.

When you put a < 0, think of it like a test of: "is a less than 0, true or false?".

So, if both a and b are negative (i.e. less than zero), their expressions will return true.

So on the line return a < 0 and b < 0, replacing and with == is like saying return true == true. Without the change it'd be return true and true.

Note: This does not mean == is the same as and. == checks for equality of the left-hand side to the right-hand side (e.g. 1 == 1) and gives a true or false value depending on the result of equality. and checks for if the left-hand side results to a true statement and if the right-hand side results to a true statement in order to result to a true expression.

CodePudding user response:

Since you're learning, you might be interested in seeing that this is an equivalent function.

  • basically it does a bit wise & and returns true if the result is < 0
  • else a bit wise exclusive or and returns true if the result is < 0
def pos_neg(a , b, negative):
      if negative:
         return (a & b) < 0  # both sign bits set (i.e. neg), return true
      else:
         return (a ^ b) < 0  # different signs, return true

In both cases, it is the sign bit of the result that is of concern. If the bit is set then the value will be negative (hence the comparison to < 0)

  • Related