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):
...
π€Piotr Dabkowski
- [Django]-GAE: ImportError while using google-auth
- [Django]-Django-pipeline throwing ValueError: the file could not be found
- [Django]-Add date to url of blog page
1π
Your code can and should be reduced to:
return self.date and self.live and self.date == now
this is because:
now <= self.date <= now
is mathematically equal toself.date == now
- 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
- [Django]-Heroku Django app not loading static files (404 Not Found)
- [Django]-How to stop Django Rest Framework from rendering html for exceptions
- [Django]-Override Model.save() for FileField handled by Boto β Django
- [Django]-Django and Suds : 'NoneType' object has no attribute 'str' in suds
- [Django]-Expect status [201] from Google Storage. But got status 302
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
- [Django]-Django 1.5 select_for_update considered fragile design
- [Django]-Django Create Multiple Objects (Same Model) From One Form
- [Django]-How can I get an access to url paramaters in django rest framework permission class?
- [Django]-Bulk insert on multi-column unique constraint Django
- [Django]-Can't "activate" virtualenv
Source:stackexchange.com