Reputation: 775
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?
Upvotes: 0
Views: 45
Reputation: 383
There actually is syntax to do this (see this answer), but you could also do something like
if max(x, y) < 0:
Upvotes: 2
Reputation: 315
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
Upvotes: 1
Reputation: 362087
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])
Upvotes: 2