47

Suppose I want to check if x belongs to range 0 to 0.5. How can I do it?

Can I use the range function for that?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user46646
  • 153,461
  • 44
  • 78
  • 84

7 Answers7

79

No, you can't do that. range() expects integer arguments. If you want to know if x is inside this range try some form of this:

print 0.0 <= x <= 0.5

Be careful with your upper limit. If you use range() it is excluded (range(0, 5) does not include 5!)

26
print 'yes' if 0 < x < 0.5 else 'no'

range() is for generating arrays of consecutive integers

vartec
  • 131,205
  • 36
  • 218
  • 244
8
>>> s = 1.1
>>> 0<= s <=0.2
False
>>> 0<= s <=1.2
True
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
8

To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.

chris
  • 1,831
  • 18
  • 33
VoidPointer
  • 17,651
  • 15
  • 54
  • 58
6

I would use the numpy library, which would allow you to do this for a list of numbers as well:

from numpy import array
a = array([1, 2, 3, 4, 5, 6,])
a[a < 2]
dalloliogm
  • 8,718
  • 6
  • 45
  • 55
6
if num in range(min, max):
  """do stuff..."""
else:
  """do other stuff..."""
b..
  • 97
  • 1
  • 5
  • 1
    This won't work for the OP's example of `float`s. See @vartec's answer. – Sanjay Manohar Aug 22 '15 at 15:50
  • Likely, this is a very slow implementation. – chris Feb 14 '18 at 23:42
  • 1
    Actually, it looks like it's implemented efficiently in CPython as `min <= num < max` (with special checks for `stride != 1`). You can check out the implementation in `range_contains` and `range_contains_long` in `cpython/Objects/rangeobject.c` – Connor Brinton Nov 14 '19 at 16:30
3

Old faithful:

if n >= a and n <= b:

And it doesn't look like Perl (joke)

Ali Afshar
  • 40,967
  • 12
  • 95
  • 109