Reputation: 36247
I have the following python code:
if bedrooms and 2 > bedrooms > 5:
bn = "BEDROOM NUMBER = " + str(bedrooms)
elif not bedrooms:
bn = "BEDROOMS DOES NOT EXIST"
I was stepping through it in my debugger and noticed that even though I thought bedroom = 0 and that the bedroom object existed the flow jumps to the elif statement.
To test this I tried:
>>> bedrooms
0.0
>>> type(bedrooms)
<type 'float'>
>>> if bedrooms and 2 > bedrooms > 5:
... print "bw"
...
Nothing was printed . Therefore it seems that 2 > bedrooms > 5 is not true? What am I doing wrong ?
addendum:
I didn't explain properly, I'm NOT looking for the number between 2-5 but rather either less than 2 or greater than 5.
Upvotes: 0
Views: 9549
Reputation: 18093
Your equality sign is reversed. For example:
>>> 2 > 4 > 5
False
Try this instead:
if bedrooms and 2 < bedrooms < 5:
This would give you the behavior, i think you're going for:
>>> 2 < 4 < 5
True
Update on Addendum: The current logic is a little awkward. Perhaps something like this:
try:
if bedrooms not in [2,3,4,5]:
bn = "BEDROOM NUMBER = {}".format(bedrooms)
except NameError:
bn = "BEDROOMS DOES NOT EXIST"
This is more semantic to me, and let's other programers more easily understand what you're trying to accomplish. This way is more explicit, and lets others know that your explicit targeting numbers not in that range, and that your handling the case that bedrooms might not exist.
This is just my 2 cents of course.
If you are expecting floats, the logic could also be:
try:
if not 2 < bedrooms > 5:
bn = "BEDROOM NUMBER = {}".format(bedrooms)
except NameError:
bn = "BEDROOMS DOES NOT EXIST"
Upvotes: 4
Reputation: 76194
There is no number that is simultaneously less than two and greater than five. You mixed up "greater than" and "less than".
if bedrooms and 2 < bedrooms < 5:
If you want a number that isn't between 2 and 5, then you can change "less than" to "less than or equal", and negate the whole thing.
if bedrooms and not (2 <= bedrooms <= 5):
Upvotes: 3