简体   繁体   中英

Python greater than and less than operands not working?

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.

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"

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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM