简体   繁体   English

Python大于和小于操作数不起作用?

[英]Python greater than and less than operands not working?

I have the following python code: 我有以下python代码:

    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. 我在调试器中逐步检查它,发现即使我认为bedroom = 0且存在bedroom对象,该流程也会跳转到elif语句。

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? 因此,似乎2>卧室> 5是不正确的? 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. 我没有正确解释,我不是在寻找2-5之间的数字,而是小于2或大于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. 当然,这只是我的2美分。


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. 没有同时小于2且大于5的数字。 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. 如果您想要的数字不在2到5之间,则可以将“小于”更改为“小于或等于”,然后取整。

if bedrooms and not (2 <= bedrooms <= 5):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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