-1

I am trying to implement an if condition where I ensure two variables are within a certain range.

But, I want to somehow do it so I don't cause duplication (Example 1 <= x,y <= 100). Is there a cleaner way to do this?

if (1 <= int(pizzeria_location_x) <= int(dimensions)) and (1 <= int(pizzeria_location_y) <= int(dimensions))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ayman.1302
  • 45
  • 4
  • 1
    cleaner way to do it would be to make the check a function for either variable is within that range – Andrew Ryan Jan 07 '23 at 22:35
  • If you have just 2 variables to check, your current code if probably the most efficient and explicit. Maybe just format it on 2 lines. – mozway Jan 07 '23 at 22:38

2 Answers2

1

You could put pizzeria_location_x and pizzeria_location_y in a tuple and evaluate the condition with all:

if all(1 <= int(l) <= int(dimensions) for l in (pizzeria_location_x, pizzeria_location_y)):
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

One option would be to use all:

if all(1 <= int(n) <= int(dimensions) for n in (pizzeria_location_x, pizzeria_location_y)):
    ...

If pizzeria_location is a tuple instead of two variables this becomes easier (and other operations may as well):

pizzeria_location = pizzeria_location_x, pizzeria_location_y
if all(1 <= int(n) <= int(dimensions) for n in pizzeria_location):
    ...
Samwise
  • 68,105
  • 3
  • 30
  • 44