Home > OS >  Can I include multiple variables in an if statement operator comparison?
Can I include multiple variables in an if statement operator comparison?

Time:01-08

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))

CodePudding user response:

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)):

CodePudding user response:

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):
    ...

CodePudding user response:

maybe a little clean way

range_bound = lambda x: 1<= x <= int(dimensions)
if range_bound(pizzeria_location_x) and range_bound(pizzeria_location_y):
  • Related