Home > Software engineering >  Can some explain the difference in outputs here?
Can some explain the difference in outputs here?

Time:01-15

I am currently doing an exercise on CodingBat that goes as follows:

Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.

This is my initial attempt:

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

CodingBat then inputs values to see if your code executes appropriately and for some reason the only input that will not run correctly is (1,-1, True).

Second attempt:

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

This attempt had no problems so it has to be the change in line 3. Can some explain the difference of if (a and b <0) and if (a < 0) and (b <0)? Why did the inputs of (1,-1, true) break it?

CodePudding user response:

if a and b < 0 is functionally equivalent to writing

if a:
    if b < 0:
        # do something

as opposed to if a < 0 and b < 0, which is functionally equivalent to writing

if a < 0:
    if b < 0:
        # do something

CodePudding user response:

The reason is that the expression a and b is doing boolean logic testing that both a and b return truthy values

When given integers it treats 0 as false and any other value as true.

the expression will actually return the last evaluated value so

1 and 0
> 0
1 and 1
> 1
1 and -1 
> -1
-1 and 1
> 1

CodePudding user response:

if a and b < 0:

The above checks the truthy value of a and that b is less than 0. a being set to any value that is not Falsy (None, ‘’, []) will make it Truthy. In other words, the above is equivalent to if bool(a) == True and b < 0:

Your modified line fixed the issue of needing to check negative on both variables.

if a < 0 and b < 0:
  •  Tags:  
  • Related