[Django]-Python chained comparison

6πŸ‘

βœ…

An example of a chained comparison is shown below.

age = 25

if 18 < age <= 25:
    print('Chained comparison!')

Note that beneath the covers this is exactly the same as shown below, it just looks nicer.

age = 25

if 18 < age and age <= 25:
    print('Chained comparison!')
πŸ‘€Ffisegydd

4πŸ‘

self.age <= now and self.age >= now

Can be simplified to:

now <= self.age <= now

But since it is True only when self.age is equal to now we can simplify the whole algorithm to:

if self.date and self.live and self.age==now:
   return True
return False

If you want to check if age is in some range then use chained comparison:

if lower<=self.age<=Upper:
     ...

Or:

if self.age in range(Lower, Upper+1):
     ...

1πŸ‘

Your code can and should be reduced to:

return self.date and self.live and self.date == now

this is because:

  1. now <= self.date <= now is mathematically equal to self.date == now
  2. if you return a boolean depending on whether a condition is true, it’s the same as just returning the result of evaluating the condition expression itself.

As to reducing a <= b and b<= c: it’s the same as a <= b <= c; and this actually works with any other operator.

πŸ‘€Erik Kaplun

0πŸ‘

To check if x is superior to 5 and inferior to 20, you can use a simplified chain comparison, i.e.:

x = 10
if 5 < x < 20:
   # yes, x is superior to 5 and x is inferior to 20
   # it's the same as: if x > 5 and x < 20:

The above is a simple example but I guess it will help new users to get started with simplified chain comparison in python

πŸ‘€Pedro Lobito

Leave a comment