code_legend
code_legend

Reputation: 3285

How to return False one of the two if statement is false?

I have the following if statement:

item_y = item[1]
item_target_y = item_target[1]
item_x = item[0]
item_target_x = item_target[0]

if (item_y + 1) != item_target_y or (item_y - 1) != item_target_y or (item_x + 1) != item_target_x or (item_y - 1) != item_target_x:
    return False

my function takes two arguments, where each argument represent a tuple. If I conduct a unitary test, this should return true

assert game((3,3),(4,4)) == True

as well as

assert game((3,3),(2,2)) == True

the item can only move diagonally up or downwards

My issue issue is that I am only able to satisfy one condition at a time and not both

My function is

   def game(item, item_target):
      return bool

Upvotes: 1

Views: 836

Answers (2)

revliscano
revliscano

Reputation: 2272

Fahd gave a correct answer. I'm just going to provide an alternative using the all() builtin function:

items = (item, item_target)
return all(items[i][j] - 1 == items[-(i - 1)][j]
           or items[i][j] + 1 == items[-(i - 1)][j]
           for i in range(1, -1, -1) for j in range(2))

It checks that all the elements of items (item and item_target tuples) match the condition: Each position's value of one tuple must be equal to the same position's value of the other tuple ± 1.

Upvotes: 1

Fahd Lyousfi
Fahd Lyousfi

Reputation: 86

Well, you are simply not telling it to return True otherwise.So the code should be something like this :

item_y = item[1]
item_target_y = item_target[1]
item_x = item[0]
item_target_x = item_target[0]

return (( (item_y + 1) == item_target_y or (item_y - 1) == item_target_y )
    and ( (item_x + 1) == item_target_x or (item_y - 1) == item_target_x ))

EDIT : I read your code and this is the function that you actually want.

Upvotes: 4

Related Questions