0

I would like to know if it is possible to do something like this in python:

if x and y < 0

insted of:

if x < 0 and y < 0

In the first case, I see that x is taken as a bool instead of int. Is there any sugar syntax for this?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
israteneda
  • 705
  • 1
  • 14
  • 26

4 Answers4

2

There actually is syntax to do this (see this answer), but you could also do something like

if max(x, y) < 0: 
wlchastain
  • 373
  • 6
  • 14
2

If you love ugly code boy you've come to the right place.

if x < 0 > y

If you have a lot of variables this one's actually decent.

if all(n < 0 for n in [x, y, z])
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

The all() builtin function allows you to test a collection of variables against a condition. Not exactly sugar, but it is generally pythonic.

if all(z < 0 for z in (x, y)):

Here is a similar SO question, along with the official python docs on this function.

Compare multiple variables to the same value in "if" in Python?

https://docs.python.org/3/library/functions.html#all

krmckone
  • 315
  • 3
  • 8
0
all(map(lambda z: z>0, [x,y]))

should do it