Chained comparison number range in Python

只愿长相守 提交于 2020-05-23 09:43:29

问题


I have the following function:

def InRange(number):
    return 5 <= number >= 1

I want this to say false if the number is not within the range of 1 to 5 using a chain comparison, but cannot seem to get this right.

Any suggestions?


回答1:


You want it like this:

def InRange(number):
    return 1 <= number <= 5

Note that you could also do:

def InRange(number):
    return 0 < number < 6



回答2:


Use this:

1 <= number <= 5

From docs:

x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Your (incorrect)expression is actually equivalent to:

number >=5 and number >= 1

So, it is going to be True for any number between 1 to infinity:




回答3:


Alternatively you can do (it seemed appropriate based on the function's name):

def InRange(number):
    return number in range(1, 6)

For large numbers you should use:

def InRange(number):
    return number in xrange(1, 10000000)


来源:https://stackoverflow.com/questions/19934892/chained-comparison-number-range-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!